blob: 68f380203f8f18497369f1b36f385e139a67c623 [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 Laurent22226012014-08-01 17:00:54 -0700218 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700219 // handle legacy remote submix case where the address was not always specified
220 if (deviceDistinguishesOnAddress(device) && (address.length() == 0)) {
221 address = String8("0");
222 }
Eric Laurente552edb2014-03-10 17:42:56 -0700223
Eric Laurent22226012014-08-01 17:00:54 -0700224 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
225 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700226
227 // connect/disconnect only 1 device at a time
228 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
229
Eric Laurente552edb2014-03-10 17:42:56 -0700230 // handle output devices
231 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700232 SortedVector <audio_io_handle_t> outputs;
233
Eric Laurent1afeecb2014-05-14 08:52:28 -0700234 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
235 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700236 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
237
Eric Laurente552edb2014-03-10 17:42:56 -0700238 // save a copy of the opened output descriptors before any output is opened or closed
239 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
240 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700241 switch (state)
242 {
243 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700244 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700245 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700246 ALOGW("setDeviceConnectionState() device already connected: %x", device);
247 return INVALID_OPERATION;
248 }
249 ALOGV("setDeviceConnectionState() connecting device %x", device);
250
Eric Laurente552edb2014-03-10 17:42:56 -0700251 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 index = mAvailableOutputDevices.add(devDesc);
253 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700254 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700255 if (module == 0) {
256 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
257 device);
258 mAvailableOutputDevices.remove(devDesc);
259 return INVALID_OPERATION;
260 }
261 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700262 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700263 } else {
264 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700265 }
266
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700267 if (checkOutputsForDevice(devDesc, state, outputs, address) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700268 mAvailableOutputDevices.remove(devDesc);
269 return INVALID_OPERATION;
270 }
271 // outputs should never be empty here
272 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
273 "checkOutputsForDevice() returned no outputs but status OK");
274 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
275 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700276 break;
277 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700278 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700279 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700280 ALOGW("setDeviceConnectionState() device not connected: %x", device);
281 return INVALID_OPERATION;
282 }
283
Paul McLean5c477aa2014-08-20 16:47:57 -0700284 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
285
286 // Set Disconnect to HALs
287 AudioParameter param = AudioParameter(address);
288 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
289 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
290
Eric Laurente552edb2014-03-10 17:42:56 -0700291 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700292 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700293
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700294 checkOutputsForDevice(devDesc, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700295 } break;
296
297 default:
298 ALOGE("setDeviceConnectionState() invalid state: %x", state);
299 return BAD_VALUE;
300 }
301
Eric Laurent3a4311c2014-03-17 12:00:47 -0700302 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
303 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700304 checkA2dpSuspend();
305 checkOutputForAllStrategies();
306 // outputs must be closed after checkOutputForAllStrategies() is executed
307 if (!outputs.isEmpty()) {
308 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700309 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700310 // close unused outputs after device disconnection or direct outputs that have been
311 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700312 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700313 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
314 (desc->mDirectOpenCount == 0))) {
315 closeOutput(outputs[i]);
316 }
317 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700318 // check again after closing A2DP output to reset mA2dpSuspended if needed
319 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700320 }
321
322 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700323 if (mPhoneState == AUDIO_MODE_IN_CALL) {
324 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
325 updateCallRouting(newDevice);
326 }
Eric Laurente552edb2014-03-10 17:42:56 -0700327 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700328 audio_io_handle_t output = mOutputs.keyAt(i);
329 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
330 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
331 true /*fromCache*/);
332 // do not force device change on duplicated output because if device is 0, it will
333 // also force a device 0 for the two outputs it is duplicated to which may override
334 // a valid device selection on those outputs.
335 bool force = !mOutputs.valueAt(i)->isDuplicated()
336 && (!deviceDistinguishesOnAddress(device)
337 // always force when disconnecting (a non-duplicated device)
338 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
339 setOutputDevice(output, newDevice, force, 0);
340 }
Eric Laurente552edb2014-03-10 17:42:56 -0700341 }
342
Eric Laurent72aa32f2014-05-30 18:51:48 -0700343 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700344 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700345 } // end if is output device
346
Eric Laurente552edb2014-03-10 17:42:56 -0700347 // handle input devices
348 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700349 SortedVector <audio_io_handle_t> inputs;
350
Eric Laurent1afeecb2014-05-14 08:52:28 -0700351 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
352 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700353 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700354 switch (state)
355 {
356 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700357 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700358 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700359 ALOGW("setDeviceConnectionState() device already connected: %d", device);
360 return INVALID_OPERATION;
361 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700362 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700363 if (module == NULL) {
364 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
365 device);
366 return INVALID_OPERATION;
367 }
Eric Laurentd4692962014-05-05 18:13:44 -0700368 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
369 return INVALID_OPERATION;
370 }
371
Eric Laurent3a4311c2014-03-17 12:00:47 -0700372 index = mAvailableInputDevices.add(devDesc);
373 if (index >= 0) {
374 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700375 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700376 } else {
377 return NO_MEMORY;
378 }
Eric Laurentd4692962014-05-05 18:13:44 -0700379 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700380
381 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700382 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700383 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700384 ALOGW("setDeviceConnectionState() device not connected: %d", device);
385 return INVALID_OPERATION;
386 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700387
388 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
389
390 // Set Disconnect to HALs
391 AudioParameter param = AudioParameter(address);
392 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
393 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
394
Eric Laurentd4692962014-05-05 18:13:44 -0700395 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700396 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700397
Eric Laurentd4692962014-05-05 18:13:44 -0700398 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700399
400 default:
401 ALOGE("setDeviceConnectionState() invalid state: %x", state);
402 return BAD_VALUE;
403 }
404
Eric Laurentd4692962014-05-05 18:13:44 -0700405 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700406
Eric Laurentc2730ba2014-07-20 15:47:07 -0700407 if (mPhoneState == AUDIO_MODE_IN_CALL) {
408 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
409 updateCallRouting(newDevice);
410 }
411
Eric Laurentb52c1522014-05-20 11:27:36 -0700412 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700413 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700414 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700415
416 ALOGW("setDeviceConnectionState() invalid device: %x", device);
417 return BAD_VALUE;
418}
419
Eric Laurente0720872014-03-11 09:30:41 -0700420audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700421 const char *device_address)
422{
Eric Laurent3b73df72014-03-11 09:06:29 -0700423 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700424 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700425 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700426 // handle legacy remote submix case where the address was not always specified
427 if (deviceDistinguishesOnAddress(device) && (devDesc->mAddress.length() == 0)) {
428 devDesc->mAddress = String8("0");
429 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700430 ssize_t index;
431 DeviceVector *deviceVector;
432
Eric Laurente552edb2014-03-10 17:42:56 -0700433 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700434 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700435 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700436 deviceVector = &mAvailableInputDevices;
437 } else {
438 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
439 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700440 }
441
Eric Laurent3a4311c2014-03-17 12:00:47 -0700442 index = deviceVector->indexOf(devDesc);
443 if (index >= 0) {
444 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
445 } else {
446 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
447 }
Eric Laurente552edb2014-03-10 17:42:56 -0700448}
449
Eric Laurentc2730ba2014-07-20 15:47:07 -0700450void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
451{
452 bool createTxPatch = false;
453 struct audio_patch patch;
454 patch.num_sources = 1;
455 patch.num_sinks = 1;
456 status_t status;
457 audio_patch_handle_t afPatchHandle;
458 DeviceVector deviceList;
459
460 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
461 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
462
463 // release existing RX patch if any
464 if (mCallRxPatch != 0) {
465 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
466 mCallRxPatch.clear();
467 }
468 // release TX patch if any
469 if (mCallTxPatch != 0) {
470 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
471 mCallTxPatch.clear();
472 }
473
474 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
475 // via setOutputDevice() on primary output.
476 // Otherwise, create two audio patches for TX and RX path.
477 if (availablePrimaryOutputDevices() & rxDevice) {
478 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
479 // If the TX device is also on the primary HW module, setOutputDevice() will take care
480 // of it due to legacy implementation. If not, create a patch.
481 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
482 == AUDIO_DEVICE_NONE) {
483 createTxPatch = true;
484 }
485 } else {
486 // create RX path audio patch
487 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
488 ALOG_ASSERT(!deviceList.isEmpty(),
489 "updateCallRouting() selected device not in output device list");
490 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
491 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
492 ALOG_ASSERT(!deviceList.isEmpty(),
493 "updateCallRouting() no telephony RX device");
494 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
495
496 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
497 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
498
499 // request to reuse existing output stream if one is already opened to reach the RX device
500 SortedVector<audio_io_handle_t> outputs =
501 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700502 audio_io_handle_t output = selectOutput(outputs,
503 AUDIO_OUTPUT_FLAG_NONE,
504 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700505 if (output != AUDIO_IO_HANDLE_NONE) {
506 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
507 ALOG_ASSERT(!outputDesc->isDuplicated(),
508 "updateCallRouting() RX device output is duplicated");
509 outputDesc->toAudioPortConfig(&patch.sources[1]);
510 patch.num_sources = 2;
511 }
512
513 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
514 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
515 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
516 status);
517 if (status == NO_ERROR) {
518 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
519 &patch, mUidCached);
520 mCallRxPatch->mAfPatchHandle = afPatchHandle;
521 mCallRxPatch->mUid = mUidCached;
522 }
523 createTxPatch = true;
524 }
525 if (createTxPatch) {
526
527 struct audio_patch patch;
528 patch.num_sources = 1;
529 patch.num_sinks = 1;
530 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
531 ALOG_ASSERT(!deviceList.isEmpty(),
532 "updateCallRouting() selected device not in input device list");
533 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
534 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
535 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
536 ALOG_ASSERT(!deviceList.isEmpty(),
537 "updateCallRouting() no telephony TX device");
538 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
539 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
540
541 SortedVector<audio_io_handle_t> outputs =
542 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700543 audio_io_handle_t output = selectOutput(outputs,
544 AUDIO_OUTPUT_FLAG_NONE,
545 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700546 // request to reuse existing output stream if one is already opened to reach the TX
547 // path output device
548 if (output != AUDIO_IO_HANDLE_NONE) {
549 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
550 ALOG_ASSERT(!outputDesc->isDuplicated(),
551 "updateCallRouting() RX device output is duplicated");
552 outputDesc->toAudioPortConfig(&patch.sources[1]);
553 patch.num_sources = 2;
554 }
555
556 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
557 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
558 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
559 status);
560 if (status == NO_ERROR) {
561 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
562 &patch, mUidCached);
563 mCallTxPatch->mAfPatchHandle = afPatchHandle;
564 mCallTxPatch->mUid = mUidCached;
565 }
566 }
567}
568
Eric Laurente0720872014-03-11 09:30:41 -0700569void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700570{
571 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700572 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700573 ALOGW("setPhoneState() invalid state %d", state);
574 return;
575 }
576
577 if (state == mPhoneState ) {
578 ALOGW("setPhoneState() setting same state %d", state);
579 return;
580 }
581
582 // if leaving call state, handle special case of active streams
583 // pertaining to sonification strategy see handleIncallSonification()
584 if (isInCall()) {
585 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700586 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800587 if (stream == AUDIO_STREAM_PATCH) {
588 continue;
589 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700590 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700591 }
592 }
593
594 // store previous phone state for management of sonification strategy below
595 int oldState = mPhoneState;
596 mPhoneState = state;
597 bool force = false;
598
599 // are we entering or starting a call
600 if (!isStateInCall(oldState) && isStateInCall(state)) {
601 ALOGV(" Entering call in setPhoneState()");
602 // force routing command to audio hardware when starting a call
603 // even if no device change is needed
604 force = true;
605 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
606 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
607 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
608 }
609 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
610 ALOGV(" Exiting call in setPhoneState()");
611 // force routing command to audio hardware when exiting a call
612 // even if no device change is needed
613 force = true;
614 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
615 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
616 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
617 }
618 } else if (isStateInCall(state) && (state != oldState)) {
619 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
620 // force routing command to audio hardware when switching between telephony and VoIP
621 // even if no device change is needed
622 force = true;
623 }
624
625 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700626 checkA2dpSuspend();
627 checkOutputForAllStrategies();
628 updateDevicesAndOutputs();
629
Eric Laurent1f2f2232014-06-02 12:01:23 -0700630 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700631
Eric Laurente552edb2014-03-10 17:42:56 -0700632 int delayMs = 0;
633 if (isStateInCall(state)) {
634 nsecs_t sysTime = systemTime();
635 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700636 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700637 // mute media and sonification strategies and delay device switch by the largest
638 // latency of any output where either strategy is active.
639 // This avoid sending the ring tone or music tail into the earpiece or headset.
640 if ((desc->isStrategyActive(STRATEGY_MEDIA,
641 SONIFICATION_HEADSET_MUSIC_DELAY,
642 sysTime) ||
643 desc->isStrategyActive(STRATEGY_SONIFICATION,
644 SONIFICATION_HEADSET_MUSIC_DELAY,
645 sysTime)) &&
646 (delayMs < (int)desc->mLatency*2)) {
647 delayMs = desc->mLatency*2;
648 }
649 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
650 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
651 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
652 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
653 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
654 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
655 }
656 }
657
Eric Laurentc2730ba2014-07-20 15:47:07 -0700658 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
659 // the device returned is not necessarily reachable via this output
660 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
661 // force routing command to audio hardware when ending call
662 // even if no device change is needed
663 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
664 rxDevice = hwOutputDesc->device();
665 }
Eric Laurente552edb2014-03-10 17:42:56 -0700666
Eric Laurentc2730ba2014-07-20 15:47:07 -0700667 if (state == AUDIO_MODE_IN_CALL) {
668 updateCallRouting(rxDevice, delayMs);
669 } else if (oldState == AUDIO_MODE_IN_CALL) {
670 if (mCallRxPatch != 0) {
671 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
672 mCallRxPatch.clear();
673 }
674 if (mCallTxPatch != 0) {
675 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
676 mCallTxPatch.clear();
677 }
678 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
679 } else {
680 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
681 }
Eric Laurente552edb2014-03-10 17:42:56 -0700682 // if entering in call state, handle special case of active streams
683 // pertaining to sonification strategy see handleIncallSonification()
684 if (isStateInCall(state)) {
685 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700686 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800687 if (stream == AUDIO_STREAM_PATCH) {
688 continue;
689 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700690 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700691 }
692 }
693
694 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700695 if (state == AUDIO_MODE_RINGTONE &&
696 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700697 mLimitRingtoneVolume = true;
698 } else {
699 mLimitRingtoneVolume = false;
700 }
701}
702
Eric Laurente0720872014-03-11 09:30:41 -0700703void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700704 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700705{
706 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
707
708 bool forceVolumeReeval = false;
709 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700710 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
711 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
712 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700713 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
714 return;
715 }
716 forceVolumeReeval = true;
717 mForceUse[usage] = config;
718 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700719 case AUDIO_POLICY_FORCE_FOR_MEDIA:
720 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
721 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
722 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
723 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Hochi Huang327cb702014-09-21 09:47:31 +0800724 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
Eric Laurente552edb2014-03-10 17:42:56 -0700725 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
726 return;
727 }
728 mForceUse[usage] = config;
729 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700730 case AUDIO_POLICY_FORCE_FOR_RECORD:
731 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
732 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700733 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
734 return;
735 }
736 mForceUse[usage] = config;
737 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700738 case AUDIO_POLICY_FORCE_FOR_DOCK:
739 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
740 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
741 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
742 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
743 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700744 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
745 }
746 forceVolumeReeval = true;
747 mForceUse[usage] = config;
748 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700749 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
750 if (config != AUDIO_POLICY_FORCE_NONE &&
751 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700752 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
753 }
754 forceVolumeReeval = true;
755 mForceUse[usage] = config;
756 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900757 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
758 if (config != AUDIO_POLICY_FORCE_NONE &&
759 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
760 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
761 }
762 mForceUse[usage] = config;
763 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700764 default:
765 ALOGW("setForceUse() invalid usage %d", usage);
766 break;
767 }
768
769 // check for device and output changes triggered by new force usage
770 checkA2dpSuspend();
771 checkOutputForAllStrategies();
772 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700773 if (mPhoneState == AUDIO_MODE_IN_CALL) {
774 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
775 updateCallRouting(newDevice);
776 }
Eric Laurente552edb2014-03-10 17:42:56 -0700777 for (size_t i = 0; i < mOutputs.size(); i++) {
778 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700779 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700780 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
781 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
782 }
Eric Laurente552edb2014-03-10 17:42:56 -0700783 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
784 applyStreamVolumes(output, newDevice, 0, true);
785 }
786 }
787
788 audio_io_handle_t activeInput = getActiveInput();
789 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700790 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700791 }
792
793}
794
Eric Laurente0720872014-03-11 09:30:41 -0700795audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700796{
797 return mForceUse[usage];
798}
799
Eric Laurente0720872014-03-11 09:30:41 -0700800void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700801{
802 ALOGV("setSystemProperty() property %s, value %s", property, value);
803}
804
805// Find a direct output profile compatible with the parameters passed, even if the input flags do
806// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700807sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700808 audio_devices_t device,
809 uint32_t samplingRate,
810 audio_format_t format,
811 audio_channel_mask_t channelMask,
812 audio_output_flags_t flags)
813{
814 for (size_t i = 0; i < mHwModules.size(); i++) {
815 if (mHwModules[i]->mHandle == 0) {
816 continue;
817 }
818 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700819 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent275e8e92014-11-30 15:14:47 -0800820 bool found = profile->isCompatibleProfile(device, String8(""), samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -0700821 NULL /*updatedSamplingRate*/, format, channelMask,
822 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
823 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700824 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
825 return profile;
826 }
Eric Laurente552edb2014-03-10 17:42:56 -0700827 }
828 }
829 return 0;
830}
831
Eric Laurente0720872014-03-11 09:30:41 -0700832audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700833 uint32_t samplingRate,
834 audio_format_t format,
835 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700836 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700837 const audio_offload_info_t *offloadInfo)
838{
Eric Laurent3b73df72014-03-11 09:06:29 -0700839 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700840 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
841 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
842 device, stream, samplingRate, format, channelMask, flags);
843
Eric Laurente83b55d2014-11-14 10:06:21 -0800844 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
845 stream, samplingRate,format, channelMask,
846 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700847}
848
Eric Laurente83b55d2014-11-14 10:06:21 -0800849status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
850 audio_io_handle_t *output,
851 audio_session_t session,
852 audio_stream_type_t *stream,
853 uint32_t samplingRate,
854 audio_format_t format,
855 audio_channel_mask_t channelMask,
856 audio_output_flags_t flags,
857 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700858{
Eric Laurente83b55d2014-11-14 10:06:21 -0800859 audio_attributes_t attributes;
860 if (attr != NULL) {
861 if (!isValidAttributes(attr)) {
862 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
863 attr->usage, attr->content_type, attr->flags,
864 attr->tags);
865 return BAD_VALUE;
866 }
867 attributes = *attr;
868 } else {
869 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
870 ALOGE("getOutputForAttr(): invalid stream type");
871 return BAD_VALUE;
872 }
873 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700874 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800875
Eric Laurent275e8e92014-11-30 15:14:47 -0800876 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
877 sp<AudioOutputDescriptor> desc;
878 if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_PLAYERS) {
879 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
880 if ((RULE_MATCH_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
881 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage == attributes.usage) ||
882 (RULE_EXCLUDE_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
883 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage != attributes.usage)) {
884 desc = mPolicyMixes[i]->mOutput;
885 break;
886 }
887 if (strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
888 strncmp(attributes.tags + strlen("addr="),
889 mPolicyMixes[i]->mMix.mRegistrationId.string(),
890 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
891 desc = mPolicyMixes[i]->mOutput;
892 break;
893 }
894 }
895 } else if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_RECORDERS) {
896 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE &&
897 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
898 strncmp(attributes.tags + strlen("addr="),
899 mPolicyMixes[i]->mMix.mRegistrationId.string(),
900 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
901 desc = mPolicyMixes[i]->mOutput;
902 break;
903 }
904 }
905 if (desc != 0) {
906 if (!audio_is_linear_pcm(format)) {
907 return BAD_VALUE;
908 }
909 desc->mPolicyMixAddress = mPolicyMixes[i]->mMix.mRegistrationId;
910 *stream = streamTypefromAttributesInt(&attributes);
911 *output = desc->mIoHandle;
912 ALOGV("getOutputForAttr() returns output %d", *output);
913 return NO_ERROR;
914 }
915 }
916 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
917 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
918 return BAD_VALUE;
919 }
920
Eric Laurent93c3d412014-08-01 14:48:35 -0700921 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800922 attributes.usage, attributes.content_type, attributes.tags, attributes.flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700923
924 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
Eric Laurente83b55d2014-11-14 10:06:21 -0800925 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700926 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700927
Eric Laurente83b55d2014-11-14 10:06:21 -0800928 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700929 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
930 }
931
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700932 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700933 device, samplingRate, format, channelMask, flags);
934
Eric Laurente83b55d2014-11-14 10:06:21 -0800935 *stream = streamTypefromAttributesInt(&attributes);
936 *output = getOutputForDevice(device, session, *stream,
937 samplingRate, format, channelMask,
938 flags, offloadInfo);
939 if (*output == AUDIO_IO_HANDLE_NONE) {
940 return INVALID_OPERATION;
941 }
942 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700943}
944
945audio_io_handle_t AudioPolicyManager::getOutputForDevice(
946 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800947 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700948 audio_stream_type_t stream,
949 uint32_t samplingRate,
950 audio_format_t format,
951 audio_channel_mask_t channelMask,
952 audio_output_flags_t flags,
953 const audio_offload_info_t *offloadInfo)
954{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700955 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700956 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700957 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700958
Eric Laurente552edb2014-03-10 17:42:56 -0700959#ifdef AUDIO_POLICY_TEST
960 if (mCurOutput != 0) {
961 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
962 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
963
964 if (mTestOutputs[mCurOutput] == 0) {
965 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700966 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700967 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700968 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700969 outputDesc->mFlags =
970 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700971 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700972 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
973 config.sample_rate = mTestSamplingRate;
974 config.channel_mask = mTestChannels;
975 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700976 if (offloadInfo != NULL) {
977 config.offload_info = *offloadInfo;
978 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700979 status = mpClientInterface->openOutput(0,
980 &mTestOutputs[mCurOutput],
981 &config,
982 &outputDesc->mDevice,
983 String8(""),
984 &outputDesc->mLatency,
985 outputDesc->mFlags);
986 if (status == NO_ERROR) {
987 outputDesc->mSamplingRate = config.sample_rate;
988 outputDesc->mFormat = config.format;
989 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700990 AudioParameter outputCmd = AudioParameter();
991 outputCmd.addInt(String8("set_id"),mCurOutput);
992 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
993 addOutput(mTestOutputs[mCurOutput], outputDesc);
994 }
995 }
996 return mTestOutputs[mCurOutput];
997 }
998#endif //AUDIO_POLICY_TEST
999
1000 // open a direct output if required by specified parameters
1001 //force direct flag if offload flag is set: offloading implies a direct output stream
1002 // and all common behaviors are driven by checking only the direct flag
1003 // this should normally be set appropriately in the policy configuration file
1004 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07001005 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001006 }
Eric Laurent93c3d412014-08-01 14:48:35 -07001007 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1008 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
1009 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001010 // only allow deep buffering for music stream type
1011 if (stream != AUDIO_STREAM_MUSIC) {
1012 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1013 }
Eric Laurente552edb2014-03-10 17:42:56 -07001014
Eric Laurentb732cf52014-09-24 19:08:21 -07001015 sp<IOProfile> profile;
1016
1017 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001018 // and not explicitly requested
1019 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1020 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -07001021 audio_channel_count_from_out_mask(channelMask) <= 2) {
1022 goto non_direct_output;
1023 }
1024
Eric Laurente552edb2014-03-10 17:42:56 -07001025 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1026 // creating an offloaded track and tearing it down immediately after start when audioflinger
1027 // detects there is an active non offloadable effect.
1028 // FIXME: We should check the audio session here but we do not have it in this context.
1029 // This may prevent offloading in rare situations where effects are left active by apps
1030 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001031
Eric Laurente552edb2014-03-10 17:42:56 -07001032 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1033 !isNonOffloadableEffectEnabled()) {
1034 profile = getProfileForDirectOutput(device,
1035 samplingRate,
1036 format,
1037 channelMask,
1038 (audio_output_flags_t)flags);
1039 }
1040
Eric Laurent1c333e22014-05-20 10:48:17 -07001041 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001042 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -07001043
1044 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001045 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001046 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1047 outputDesc = desc;
1048 // reuse direct output if currently open and configured with same parameters
1049 if ((samplingRate == outputDesc->mSamplingRate) &&
1050 (format == outputDesc->mFormat) &&
1051 (channelMask == outputDesc->mChannelMask)) {
1052 outputDesc->mDirectOpenCount++;
1053 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
1054 return mOutputs.keyAt(i);
1055 }
1056 }
1057 }
1058 // close direct output if currently open and configured with different parameters
1059 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001060 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001061 }
1062 outputDesc = new AudioOutputDescriptor(profile);
1063 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001064 outputDesc->mLatency = 0;
1065 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001066 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1067 config.sample_rate = samplingRate;
1068 config.channel_mask = channelMask;
1069 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001070 if (offloadInfo != NULL) {
1071 config.offload_info = *offloadInfo;
1072 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001073 status = mpClientInterface->openOutput(profile->mModule->mHandle,
1074 &output,
1075 &config,
1076 &outputDesc->mDevice,
1077 String8(""),
1078 &outputDesc->mLatency,
1079 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001080
1081 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001082 if (status != NO_ERROR ||
1083 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1084 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1085 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001086 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1087 "format %d %d, channelMask %04x %04x", output, samplingRate,
1088 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1089 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001090 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001091 mpClientInterface->closeOutput(output);
1092 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001093 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001094 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001095 outputDesc->mSamplingRate = config.sample_rate;
1096 outputDesc->mChannelMask = config.channel_mask;
1097 outputDesc->mFormat = config.format;
1098 outputDesc->mRefCount[stream] = 0;
1099 outputDesc->mStopTime[stream] = 0;
1100 outputDesc->mDirectOpenCount = 1;
1101
Eric Laurente552edb2014-03-10 17:42:56 -07001102 audio_io_handle_t srcOutput = getOutputForEffect();
1103 addOutput(output, outputDesc);
1104 audio_io_handle_t dstOutput = getOutputForEffect();
1105 if (dstOutput == output) {
1106 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1107 }
1108 mPreviousOutputs = mOutputs;
1109 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001110 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001111 return output;
1112 }
1113
Eric Laurentb732cf52014-09-24 19:08:21 -07001114non_direct_output:
1115
Eric Laurente552edb2014-03-10 17:42:56 -07001116 // ignoring channel mask due to downmix capability in mixer
1117
1118 // open a non direct output
1119
1120 // for non direct outputs, only PCM is supported
1121 if (audio_is_linear_pcm(format)) {
1122 // get which output is suitable for the specified stream. The actual
1123 // routing change will happen when startOutput() will be called
1124 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1125
Eric Laurent8838a382014-09-08 16:44:28 -07001126 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1127 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1128 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001129 }
1130 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1131 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1132
1133 ALOGV("getOutput() returns output %d", output);
1134
1135 return output;
1136}
1137
Eric Laurente0720872014-03-11 09:30:41 -07001138audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001139 audio_output_flags_t flags,
1140 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001141{
1142 // select one output among several that provide a path to a particular device or set of
1143 // devices (the list was previously build by getOutputsForDevice()).
1144 // The priority is as follows:
1145 // 1: the output with the highest number of requested policy flags
1146 // 2: the primary output
1147 // 3: the first output in the list
1148
1149 if (outputs.size() == 0) {
1150 return 0;
1151 }
1152 if (outputs.size() == 1) {
1153 return outputs[0];
1154 }
1155
1156 int maxCommonFlags = 0;
1157 audio_io_handle_t outputFlags = 0;
1158 audio_io_handle_t outputPrimary = 0;
1159
1160 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001161 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001162 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001163 // if a valid format is specified, skip output if not compatible
1164 if (format != AUDIO_FORMAT_INVALID) {
1165 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1166 if (format != outputDesc->mFormat) {
1167 continue;
1168 }
1169 } else if (!audio_is_linear_pcm(format)) {
1170 continue;
1171 }
1172 }
1173
Eric Laurent3b73df72014-03-11 09:06:29 -07001174 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001175 if (commonFlags > maxCommonFlags) {
1176 outputFlags = outputs[i];
1177 maxCommonFlags = commonFlags;
1178 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1179 }
1180 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1181 outputPrimary = outputs[i];
1182 }
1183 }
1184 }
1185
1186 if (outputFlags != 0) {
1187 return outputFlags;
1188 }
1189 if (outputPrimary != 0) {
1190 return outputPrimary;
1191 }
1192
1193 return outputs[0];
1194}
1195
Eric Laurente0720872014-03-11 09:30:41 -07001196status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001197 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001198 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001199{
1200 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1201 ssize_t index = mOutputs.indexOfKey(output);
1202 if (index < 0) {
1203 ALOGW("startOutput() unknown output %d", output);
1204 return BAD_VALUE;
1205 }
1206
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001207 // cannot start playback of STREAM_TTS if any other output is being used
1208 uint32_t beaconMuteLatency = 0;
1209 if (stream == AUDIO_STREAM_TTS) {
1210 ALOGV("\t found BEACON stream");
1211 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1212 return INVALID_OPERATION;
1213 } else {
1214 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1215 }
1216 } else {
1217 // some playback other than beacon starts
1218 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1219 }
1220
Eric Laurent1f2f2232014-06-02 12:01:23 -07001221 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001222
1223 // increment usage count for this stream on the requested output:
1224 // NOTE that the usage count is the same for duplicated output and hardware output which is
1225 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1226 outputDesc->changeRefCount(stream, 1);
1227
1228 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001229 // starting an output being rerouted?
1230 audio_devices_t newDevice;
1231 if (outputDesc->mPolicyMixAddress != String8("")
1232 && outputDesc->mPolicyMixAddress != String8("0")) {
1233 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1234 } else {
1235 newDevice = getNewOutputDevice(output, false /*fromCache*/);
1236 }
Eric Laurente552edb2014-03-10 17:42:56 -07001237 routing_strategy strategy = getStrategy(stream);
1238 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001239 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1240 (beaconMuteLatency > 0);
1241 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001242 bool force = false;
1243 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001244 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001245 if (desc != outputDesc) {
1246 // force a device change if any other output is managed by the same hw
1247 // module and has a current device selection that differs from selected device.
1248 // In this case, the audio HAL must receive the new device selection so that it can
1249 // change the device currently selected by the other active output.
1250 if (outputDesc->sharesHwModuleWith(desc) &&
1251 desc->device() != newDevice) {
1252 force = true;
1253 }
1254 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001255 // a notification so that audio focus effect can propagate, or that a mute/unmute
1256 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001257 uint32_t latency = desc->latency();
1258 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1259 waitMs = latency;
1260 }
1261 }
1262 }
1263 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1264
1265 // handle special case for sonification while in call
1266 if (isInCall()) {
1267 handleIncallSonification(stream, true, false);
1268 }
1269
1270 // apply volume rules for current stream and device if necessary
1271 checkAndSetVolume(stream,
1272 mStreams[stream].getVolumeIndex(newDevice),
1273 output,
1274 newDevice);
1275
1276 // update the outputs if starting an output with a stream that can affect notification
1277 // routing
1278 handleNotificationRoutingForStream(stream);
1279 if (waitMs > muteWaitMs) {
1280 usleep((waitMs - muteWaitMs) * 2 * 1000);
1281 }
1282 }
1283 return NO_ERROR;
1284}
1285
1286
Eric Laurente0720872014-03-11 09:30:41 -07001287status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001288 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001289 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001290{
1291 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1292 ssize_t index = mOutputs.indexOfKey(output);
1293 if (index < 0) {
1294 ALOGW("stopOutput() unknown output %d", output);
1295 return BAD_VALUE;
1296 }
1297
Eric Laurent1f2f2232014-06-02 12:01:23 -07001298 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001299
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001300 // always handle stream stop, check which stream type is stopping
1301 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1302
Eric Laurente552edb2014-03-10 17:42:56 -07001303 // handle special case for sonification while in call
1304 if (isInCall()) {
1305 handleIncallSonification(stream, false, false);
1306 }
1307
1308 if (outputDesc->mRefCount[stream] > 0) {
1309 // decrement usage count of this stream on the output
1310 outputDesc->changeRefCount(stream, -1);
1311 // store time at which the stream was stopped - see isStreamActive()
1312 if (outputDesc->mRefCount[stream] == 0) {
1313 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001314 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001315 // delay the device switch by twice the latency because stopOutput() is executed when
1316 // the track stop() command is received and at that time the audio track buffer can
1317 // still contain data that needs to be drained. The latency only covers the audio HAL
1318 // and kernel buffers. Also the latency does not always include additional delay in the
1319 // audio path (audio DSP, CODEC ...)
1320 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1321
1322 // force restoring the device selection on other active outputs if it differs from the
1323 // one being selected for this output
1324 for (size_t i = 0; i < mOutputs.size(); i++) {
1325 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001326 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001327 if (curOutput != output &&
1328 desc->isActive() &&
1329 outputDesc->sharesHwModuleWith(desc) &&
1330 (newDevice != desc->device())) {
1331 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001332 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001333 true,
1334 outputDesc->mLatency*2);
1335 }
1336 }
1337 // update the outputs if stopping one with a stream that can affect notification routing
1338 handleNotificationRoutingForStream(stream);
1339 }
1340 return NO_ERROR;
1341 } else {
1342 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1343 return INVALID_OPERATION;
1344 }
1345}
1346
Eric Laurente83b55d2014-11-14 10:06:21 -08001347void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001348 audio_stream_type_t stream __unused,
1349 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001350{
1351 ALOGV("releaseOutput() %d", output);
1352 ssize_t index = mOutputs.indexOfKey(output);
1353 if (index < 0) {
1354 ALOGW("releaseOutput() releasing unknown output %d", output);
1355 return;
1356 }
1357
1358#ifdef AUDIO_POLICY_TEST
1359 int testIndex = testOutputIndex(output);
1360 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001361 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001362 if (outputDesc->isActive()) {
1363 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001364 mOutputs.removeItem(output);
1365 mTestOutputs[testIndex] = 0;
1366 }
1367 return;
1368 }
1369#endif //AUDIO_POLICY_TEST
1370
Eric Laurent1f2f2232014-06-02 12:01:23 -07001371 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001372 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001373 if (desc->mDirectOpenCount <= 0) {
1374 ALOGW("releaseOutput() invalid open count %d for output %d",
1375 desc->mDirectOpenCount, output);
1376 return;
1377 }
1378 if (--desc->mDirectOpenCount == 0) {
1379 closeOutput(output);
1380 // If effects where present on the output, audioflinger moved them to the primary
1381 // output by default: move them back to the appropriate output.
1382 audio_io_handle_t dstOutput = getOutputForEffect();
1383 if (dstOutput != mPrimaryOutput) {
1384 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1385 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001386 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001387 }
1388 }
1389}
1390
1391
Eric Laurentcaf7f482014-11-25 17:50:47 -08001392status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1393 audio_io_handle_t *input,
1394 audio_session_t session,
1395 uint32_t samplingRate,
1396 audio_format_t format,
1397 audio_channel_mask_t channelMask,
1398 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001399{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001400 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1401 "session %d, flags %#x",
1402 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001403
Eric Laurentcaf7f482014-11-25 17:50:47 -08001404 *input = AUDIO_IO_HANDLE_NONE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001405 audio_devices_t device;
1406 // handle legacy remote submix case where the address was not always specified
1407 String8 address = String8("");
Eric Laurent5dbe4712014-09-19 19:04:57 -07001408 bool isSoundTrigger = false;
Eric Laurentcaf7f482014-11-25 17:50:47 -08001409 audio_source_t halInputSource = attr->source;
Eric Laurent275e8e92014-11-30 15:14:47 -08001410
1411 if (attr->source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1412 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
1413 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1414 address = String8(attr->tags + strlen("addr="));
1415 ssize_t index = mPolicyMixes.indexOfKey(address);
1416 if (index < 0) {
1417 ALOGW("getInputForAttr() no policy for address %s", address.string());
1418 return BAD_VALUE;
1419 }
1420 } else {
1421 device = getDeviceForInputSource(attr->source, &address);
1422
1423 if (device == AUDIO_DEVICE_NONE) {
1424 ALOGW("getInputForAttr() could not find device for source %d", attr->source);
1425 return BAD_VALUE;
1426 }
1427 // adapt channel selection to input source
1428 switch (attr->source) {
1429 case AUDIO_SOURCE_VOICE_UPLINK:
1430 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1431 break;
1432 case AUDIO_SOURCE_VOICE_DOWNLINK:
1433 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1434 break;
1435 case AUDIO_SOURCE_VOICE_CALL:
1436 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1437 break;
1438 default:
1439 break;
1440 }
1441 if (attr->source == AUDIO_SOURCE_HOTWORD) {
1442 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1443 if (index >= 0) {
1444 *input = mSoundTriggerSessions.valueFor(session);
1445 isSoundTrigger = true;
1446 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1447 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
1448 } else {
1449 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1450 }
Eric Laurent5dbe4712014-09-19 19:04:57 -07001451 }
1452 }
1453
Eric Laurent275e8e92014-11-30 15:14:47 -08001454 sp<IOProfile> profile = getInputProfile(device, address,
1455 samplingRate, format, channelMask,
1456 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001457 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001458 //retry without flags
1459 audio_input_flags_t log_flags = flags;
1460 flags = AUDIO_INPUT_FLAG_NONE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001461 profile = getInputProfile(device, address,
1462 samplingRate, format, channelMask,
1463 flags);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001464 if (profile == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001465 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1466 "format %#x, channelMask 0x%X, flags %#x",
Eric Laurent5dbe4712014-09-19 19:04:57 -07001467 device, samplingRate, format, channelMask, log_flags);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001468 return BAD_VALUE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001469 }
Eric Laurente552edb2014-03-10 17:42:56 -07001470 }
1471
1472 if (profile->mModule->mHandle == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001473 ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName);
1474 return NO_INIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001475 }
1476
1477 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1478 config.sample_rate = samplingRate;
1479 config.channel_mask = channelMask;
1480 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001481
Eric Laurentcf2c0212014-07-25 16:20:43 -07001482 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001483 input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001484 &config,
1485 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001486 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001487 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001488 flags);
1489
1490 // only accept input with the exact requested set of parameters
Eric Laurentcaf7f482014-11-25 17:50:47 -08001491 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001492 (samplingRate != config.sample_rate) ||
1493 (format != config.format) ||
1494 (channelMask != config.channel_mask)) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001495 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001496 samplingRate, format, channelMask);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001497 if (*input != AUDIO_IO_HANDLE_NONE) {
1498 mpClientInterface->closeInput(*input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001499 }
Eric Laurentcaf7f482014-11-25 17:50:47 -08001500 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001501 }
1502
Eric Laurent1f2f2232014-06-02 12:01:23 -07001503 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001504 inputDesc->mInputSource = attr->source;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001505 inputDesc->mRefCount = 0;
1506 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001507 inputDesc->mSamplingRate = samplingRate;
1508 inputDesc->mFormat = format;
1509 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001510 inputDesc->mDevice = device;
Eric Laurent275e8e92014-11-30 15:14:47 -08001511 inputDesc->mSessions.add(session, address);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001512 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001513
Eric Laurentcaf7f482014-11-25 17:50:47 -08001514 addInput(*input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001515 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcaf7f482014-11-25 17:50:47 -08001516 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001517}
1518
Eric Laurent4dc68062014-07-28 17:26:49 -07001519status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1520 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001521{
1522 ALOGV("startInput() input %d", input);
1523 ssize_t index = mInputs.indexOfKey(input);
1524 if (index < 0) {
1525 ALOGW("startInput() unknown input %d", input);
1526 return BAD_VALUE;
1527 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001528 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001529
Eric Laurent275e8e92014-11-30 15:14:47 -08001530 index = inputDesc->mSessions.indexOfKey(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001531 if (index < 0) {
1532 ALOGW("startInput() unknown session %d on input %d", session, input);
1533 return BAD_VALUE;
1534 }
1535
Glenn Kasten74a8e252014-07-24 14:09:55 -07001536 // virtual input devices are compatible with other input devices
1537 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1538
1539 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001540 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001541 if (activeInput != 0 && activeInput != input) {
1542
1543 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1544 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001545 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001546 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001547 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent275e8e92014-11-30 15:14:47 -08001548 stopInput(activeInput, activeDesc->mSessions.keyAt(0));
1549 releaseInput(activeInput, activeDesc->mSessions.keyAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001550 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001551 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001552 return INVALID_OPERATION;
1553 }
1554 }
1555 }
1556
Glenn Kasten74a8e252014-07-24 14:09:55 -07001557 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001558 if (activeInputsCount() == 0) {
1559 SoundTrigger::setCaptureState(true);
1560 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001561 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001562
Glenn Kasten74a8e252014-07-24 14:09:55 -07001563 // Automatically enable the remote submix output when input is started.
1564 // For remote submix (a virtual device), we open only one input per capture request.
1565 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1566 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08001567 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1568 inputDesc->mSessions.valueAt(index));
Glenn Kasten74a8e252014-07-24 14:09:55 -07001569 }
Eric Laurente552edb2014-03-10 17:42:56 -07001570 }
1571
Eric Laurente552edb2014-03-10 17:42:56 -07001572 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1573
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001574 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001575 return NO_ERROR;
1576}
1577
Eric Laurent4dc68062014-07-28 17:26:49 -07001578status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1579 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001580{
1581 ALOGV("stopInput() input %d", input);
1582 ssize_t index = mInputs.indexOfKey(input);
1583 if (index < 0) {
1584 ALOGW("stopInput() unknown input %d", input);
1585 return BAD_VALUE;
1586 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001587 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001588
Eric Laurent275e8e92014-11-30 15:14:47 -08001589 index = inputDesc->mSessions.indexOfKey(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001590 if (index < 0) {
1591 ALOGW("stopInput() unknown session %d on input %d", session, input);
1592 return BAD_VALUE;
1593 }
1594
Eric Laurente552edb2014-03-10 17:42:56 -07001595 if (inputDesc->mRefCount == 0) {
1596 ALOGW("stopInput() input %d already stopped", input);
1597 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001598 }
1599
1600 inputDesc->mRefCount--;
1601 if (inputDesc->mRefCount == 0) {
1602
Eric Laurente552edb2014-03-10 17:42:56 -07001603 // automatically disable the remote submix output when input is stopped
1604 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1605 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08001606 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1607 inputDesc->mSessions.valueAt(index));
Eric Laurente552edb2014-03-10 17:42:56 -07001608 }
1609
Eric Laurent1c333e22014-05-20 10:48:17 -07001610 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001611
1612 if (activeInputsCount() == 0) {
1613 SoundTrigger::setCaptureState(false);
1614 }
Eric Laurente552edb2014-03-10 17:42:56 -07001615 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001616 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001617}
1618
Eric Laurent4dc68062014-07-28 17:26:49 -07001619void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1620 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001621{
1622 ALOGV("releaseInput() %d", input);
1623 ssize_t index = mInputs.indexOfKey(input);
1624 if (index < 0) {
1625 ALOGW("releaseInput() releasing unknown input %d", input);
1626 return;
1627 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001628 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1629 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001630
Eric Laurent275e8e92014-11-30 15:14:47 -08001631 index = inputDesc->mSessions.indexOfKey(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001632 if (index < 0) {
1633 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1634 return;
1635 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001636 inputDesc->mSessions.removeItem(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001637 if (inputDesc->mOpenRefCount == 0) {
1638 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1639 return;
1640 }
1641 inputDesc->mOpenRefCount--;
1642 if (inputDesc->mOpenRefCount > 0) {
1643 ALOGV("releaseInput() exit > 0");
1644 return;
1645 }
1646
Eric Laurent05b90f82014-08-27 15:32:29 -07001647 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001648 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001649 ALOGV("releaseInput() exit");
1650}
1651
Eric Laurentd4692962014-05-05 18:13:44 -07001652void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001653 bool patchRemoved = false;
1654
Eric Laurentd4692962014-05-05 18:13:44 -07001655 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001656 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1657 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1658 if (patch_index >= 0) {
1659 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1660 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1661 mAudioPatches.removeItemsAt(patch_index);
1662 patchRemoved = true;
1663 }
Eric Laurentd4692962014-05-05 18:13:44 -07001664 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1665 }
1666 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001667 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001668
1669 if (patchRemoved) {
1670 mpClientInterface->onAudioPatchListUpdate();
1671 }
Eric Laurentd4692962014-05-05 18:13:44 -07001672}
1673
Eric Laurente0720872014-03-11 09:30:41 -07001674void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001675 int indexMin,
1676 int indexMax)
1677{
1678 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1679 if (indexMin < 0 || indexMin >= indexMax) {
1680 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1681 return;
1682 }
1683 mStreams[stream].mIndexMin = indexMin;
1684 mStreams[stream].mIndexMax = indexMax;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001685 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1686 if (stream == AUDIO_STREAM_MUSIC) {
1687 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1688 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1689 }
Eric Laurente552edb2014-03-10 17:42:56 -07001690}
1691
Eric Laurente0720872014-03-11 09:30:41 -07001692status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001693 int index,
1694 audio_devices_t device)
1695{
1696
1697 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1698 return BAD_VALUE;
1699 }
1700 if (!audio_is_output_device(device)) {
1701 return BAD_VALUE;
1702 }
1703
1704 // Force max volume if stream cannot be muted
1705 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1706
1707 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1708 stream, device, index);
1709
1710 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1711 // clear all device specific values
1712 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1713 mStreams[stream].mIndexCur.clear();
1714 }
1715 mStreams[stream].mIndexCur.add(device, index);
1716
Eric Laurent31551f82014-10-10 18:21:56 -07001717 // update volume on all outputs whose current device is also selected by the same
1718 // strategy as the device specified by the caller
1719 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001720
1721
1722 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1723 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1724 if (stream == AUDIO_STREAM_MUSIC) {
1725 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1726 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1727 }
1728 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1729 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001730 return NO_ERROR;
1731 }
Eric Laurente552edb2014-03-10 17:42:56 -07001732 status_t status = NO_ERROR;
1733 for (size_t i = 0; i < mOutputs.size(); i++) {
1734 audio_devices_t curDevice =
1735 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001736 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001737 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1738 if (volStatus != NO_ERROR) {
1739 status = volStatus;
1740 }
1741 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001742 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1743 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1744 index, mOutputs.keyAt(i), curDevice);
1745 }
Eric Laurente552edb2014-03-10 17:42:56 -07001746 }
1747 return status;
1748}
1749
Eric Laurente0720872014-03-11 09:30:41 -07001750status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001751 int *index,
1752 audio_devices_t device)
1753{
1754 if (index == NULL) {
1755 return BAD_VALUE;
1756 }
1757 if (!audio_is_output_device(device)) {
1758 return BAD_VALUE;
1759 }
1760 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1761 // the strategy the stream belongs to.
1762 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1763 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1764 }
1765 device = getDeviceForVolume(device);
1766
1767 *index = mStreams[stream].getVolumeIndex(device);
1768 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1769 return NO_ERROR;
1770}
1771
Eric Laurente0720872014-03-11 09:30:41 -07001772audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001773 const SortedVector<audio_io_handle_t>& outputs)
1774{
1775 // select one output among several suitable for global effects.
1776 // The priority is as follows:
1777 // 1: An offloaded output. If the effect ends up not being offloadable,
1778 // AudioFlinger will invalidate the track and the offloaded output
1779 // will be closed causing the effect to be moved to a PCM output.
1780 // 2: A deep buffer output
1781 // 3: the first output in the list
1782
1783 if (outputs.size() == 0) {
1784 return 0;
1785 }
1786
1787 audio_io_handle_t outputOffloaded = 0;
1788 audio_io_handle_t outputDeepBuffer = 0;
1789
1790 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001791 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001792 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001793 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1794 outputOffloaded = outputs[i];
1795 }
1796 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1797 outputDeepBuffer = outputs[i];
1798 }
1799 }
1800
1801 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1802 outputOffloaded, outputDeepBuffer);
1803 if (outputOffloaded != 0) {
1804 return outputOffloaded;
1805 }
1806 if (outputDeepBuffer != 0) {
1807 return outputDeepBuffer;
1808 }
1809
1810 return outputs[0];
1811}
1812
Eric Laurente0720872014-03-11 09:30:41 -07001813audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001814{
1815 // apply simple rule where global effects are attached to the same output as MUSIC streams
1816
Eric Laurent3b73df72014-03-11 09:06:29 -07001817 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001818 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1819 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1820
1821 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1822 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1823 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1824
1825 return output;
1826}
1827
Eric Laurente0720872014-03-11 09:30:41 -07001828status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001829 audio_io_handle_t io,
1830 uint32_t strategy,
1831 int session,
1832 int id)
1833{
1834 ssize_t index = mOutputs.indexOfKey(io);
1835 if (index < 0) {
1836 index = mInputs.indexOfKey(io);
1837 if (index < 0) {
1838 ALOGW("registerEffect() unknown io %d", io);
1839 return INVALID_OPERATION;
1840 }
1841 }
1842
1843 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1844 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1845 desc->name, desc->memoryUsage);
1846 return INVALID_OPERATION;
1847 }
1848 mTotalEffectsMemory += desc->memoryUsage;
1849 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1850 desc->name, io, strategy, session, id);
1851 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1852
Eric Laurent1f2f2232014-06-02 12:01:23 -07001853 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1854 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1855 effectDesc->mIo = io;
1856 effectDesc->mStrategy = (routing_strategy)strategy;
1857 effectDesc->mSession = session;
1858 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001859
Eric Laurent1f2f2232014-06-02 12:01:23 -07001860 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001861
1862 return NO_ERROR;
1863}
1864
Eric Laurente0720872014-03-11 09:30:41 -07001865status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001866{
1867 ssize_t index = mEffects.indexOfKey(id);
1868 if (index < 0) {
1869 ALOGW("unregisterEffect() unknown effect ID %d", id);
1870 return INVALID_OPERATION;
1871 }
1872
Eric Laurent1f2f2232014-06-02 12:01:23 -07001873 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001874
Eric Laurent1f2f2232014-06-02 12:01:23 -07001875 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001876
Eric Laurent1f2f2232014-06-02 12:01:23 -07001877 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001878 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001879 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1880 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001881 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001882 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001883 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001884 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001885
1886 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001887
1888 return NO_ERROR;
1889}
1890
Eric Laurente0720872014-03-11 09:30:41 -07001891status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001892{
1893 ssize_t index = mEffects.indexOfKey(id);
1894 if (index < 0) {
1895 ALOGW("unregisterEffect() unknown effect ID %d", id);
1896 return INVALID_OPERATION;
1897 }
1898
1899 return setEffectEnabled(mEffects.valueAt(index), enabled);
1900}
1901
Eric Laurent1f2f2232014-06-02 12:01:23 -07001902status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001903{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001904 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001905 ALOGV("setEffectEnabled(%s) effect already %s",
1906 enabled?"true":"false", enabled?"enabled":"disabled");
1907 return INVALID_OPERATION;
1908 }
1909
1910 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001911 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001912 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001913 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001914 return INVALID_OPERATION;
1915 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001916 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001917 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1918 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001919 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001920 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001921 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1922 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001923 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001924 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001925 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1926 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001927 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001928 return NO_ERROR;
1929}
1930
Eric Laurente0720872014-03-11 09:30:41 -07001931bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001932{
1933 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001934 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1935 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1936 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001937 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001938 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001939 return true;
1940 }
1941 }
1942 return false;
1943}
1944
Eric Laurente0720872014-03-11 09:30:41 -07001945bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001946{
1947 nsecs_t sysTime = systemTime();
1948 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001949 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001950 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001951 return true;
1952 }
1953 }
1954 return false;
1955}
1956
Eric Laurente0720872014-03-11 09:30:41 -07001957bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001958 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001959{
1960 nsecs_t sysTime = systemTime();
1961 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001962 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001963 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001964 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001965 return true;
1966 }
1967 }
1968 return false;
1969}
1970
Eric Laurente0720872014-03-11 09:30:41 -07001971bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001972{
1973 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001974 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001975 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001976 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001977 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1978 && (inputDescriptor->mRefCount > 0)) {
1979 return true;
1980 }
1981 }
1982 return false;
1983}
1984
Eric Laurent275e8e92014-11-30 15:14:47 -08001985// Register a list of custom mixes with their attributes and format.
1986// When a mix is registered, corresponding input and output profiles are
1987// added to the remote submix hw module. The profile contains only the
1988// parameters (sampling rate, format...) specified by the mix.
1989// The corresponding input remote submix device is also connected.
1990//
1991// When a remote submix device is connected, the address is checked to select the
1992// appropriate profile and the corresponding input or output stream is opened.
1993//
1994// When capture starts, getInputForAttr() will:
1995// - 1 look for a mix matching the address passed in attribtutes tags if any
1996// - 2 if none found, getDeviceForInputSource() will:
1997// - 2.1 look for a mix matching the attributes source
1998// - 2.2 if none found, default to device selection by policy rules
1999// At this time, the corresponding output remote submix device is also connected
2000// and active playback use cases can be transferred to this mix if needed when reconnecting
2001// after AudioTracks are invalidated
2002//
2003// When playback starts, getOutputForAttr() will:
2004// - 1 look for a mix matching the address passed in attribtutes tags if any
2005// - 2 if none found, look for a mix matching the attributes usage
2006// - 3 if none found, default to device and output selection by policy rules.
2007
2008status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2009{
2010 sp<HwModule> module;
2011 for (size_t i = 0; i < mHwModules.size(); i++) {
2012 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2013 mHwModules[i]->mHandle != 0) {
2014 module = mHwModules[i];
2015 break;
2016 }
2017 }
2018
2019 if (module == 0) {
2020 return INVALID_OPERATION;
2021 }
2022
2023 ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
2024
2025 for (size_t i = 0; i < mixes.size(); i++) {
2026 String8 address = mixes[i].mRegistrationId;
2027 ssize_t index = mPolicyMixes.indexOfKey(address);
2028 if (index >= 0) {
2029 ALOGE("registerPolicyMixes(): mix for address %s already registered", address.string());
2030 continue;
2031 }
2032 audio_config_t outputConfig = mixes[i].mFormat;
2033 audio_config_t inputConfig = mixes[i].mFormat;
2034 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2035 // stereo and let audio flinger do the channel conversion if needed.
2036 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2037 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2038 module->addOutputProfile(address, &outputConfig,
2039 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2040 module->addInputProfile(address, &inputConfig,
2041 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2042 sp<AudioPolicyMix> policyMix = new AudioPolicyMix();
2043 policyMix->mMix = mixes[i];
2044 mPolicyMixes.add(address, policyMix);
2045 setDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2046 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2047 address.string());
2048 }
2049 return NO_ERROR;
2050}
2051
2052status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2053{
2054 sp<HwModule> module;
2055 for (size_t i = 0; i < mHwModules.size(); i++) {
2056 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2057 mHwModules[i]->mHandle != 0) {
2058 module = mHwModules[i];
2059 break;
2060 }
2061 }
2062
2063 if (module == 0) {
2064 return INVALID_OPERATION;
2065 }
2066
2067 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
2068
2069 for (size_t i = 0; i < mixes.size(); i++) {
2070 String8 address = mixes[i].mRegistrationId;
2071 ssize_t index = mPolicyMixes.indexOfKey(address);
2072 if (index < 0) {
2073 ALOGE("unregisterPolicyMixes(): mix for address %s not registered", address.string());
2074 continue;
2075 }
2076
2077 mPolicyMixes.removeItemsAt(index);
2078
2079 setDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2080 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2081 address.string());
2082
2083 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2084 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2085 {
2086 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2087 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2088 address.string());
2089 }
2090 module->removeOutputProfile(address);
2091 module->removeInputProfile(address);
2092 }
2093 return NO_ERROR;
2094}
2095
Eric Laurente552edb2014-03-10 17:42:56 -07002096
Eric Laurente0720872014-03-11 09:30:41 -07002097status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002098{
2099 const size_t SIZE = 256;
2100 char buffer[SIZE];
2101 String8 result;
2102
2103 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2104 result.append(buffer);
2105
2106 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
2107 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002108 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
2109 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002110 snprintf(buffer, SIZE, " Force use for communications %d\n",
2111 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07002112 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002113 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07002114 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002115 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07002116 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002117 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07002118 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002119 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07002120 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002121 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2122 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
2123 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002124
Eric Laurent3a4311c2014-03-17 12:00:47 -07002125 snprintf(buffer, SIZE, " Available output devices:\n");
2126 result.append(buffer);
2127 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002128 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002129 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002130 }
2131 snprintf(buffer, SIZE, "\n Available input devices:\n");
2132 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07002133 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002134 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002135 }
Eric Laurente552edb2014-03-10 17:42:56 -07002136
2137 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
2138 write(fd, buffer, strlen(buffer));
2139 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002140 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002141 write(fd, buffer, strlen(buffer));
2142 mHwModules[i]->dump(fd);
2143 }
2144
2145 snprintf(buffer, SIZE, "\nOutputs dump:\n");
2146 write(fd, buffer, strlen(buffer));
2147 for (size_t i = 0; i < mOutputs.size(); i++) {
2148 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
2149 write(fd, buffer, strlen(buffer));
2150 mOutputs.valueAt(i)->dump(fd);
2151 }
2152
2153 snprintf(buffer, SIZE, "\nInputs dump:\n");
2154 write(fd, buffer, strlen(buffer));
2155 for (size_t i = 0; i < mInputs.size(); i++) {
2156 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
2157 write(fd, buffer, strlen(buffer));
2158 mInputs.valueAt(i)->dump(fd);
2159 }
2160
2161 snprintf(buffer, SIZE, "\nStreams dump:\n");
2162 write(fd, buffer, strlen(buffer));
2163 snprintf(buffer, SIZE,
2164 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
2165 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002166 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002167 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07002168 write(fd, buffer, strlen(buffer));
2169 mStreams[i].dump(fd);
2170 }
2171
2172 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2173 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2174 write(fd, buffer, strlen(buffer));
2175
2176 snprintf(buffer, SIZE, "Registered effects:\n");
2177 write(fd, buffer, strlen(buffer));
2178 for (size_t i = 0; i < mEffects.size(); i++) {
2179 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2180 write(fd, buffer, strlen(buffer));
2181 mEffects.valueAt(i)->dump(fd);
2182 }
2183
Eric Laurent4d416952014-08-10 14:07:09 -07002184 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2185 write(fd, buffer, strlen(buffer));
2186 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2187 mAudioPatches[i]->dump(fd, 2, i);
2188 }
Eric Laurente552edb2014-03-10 17:42:56 -07002189
2190 return NO_ERROR;
2191}
2192
2193// This function checks for the parameters which can be offloaded.
2194// This can be enhanced depending on the capability of the DSP and policy
2195// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002196bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002197{
2198 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002199 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002200 offloadInfo.sample_rate, offloadInfo.channel_mask,
2201 offloadInfo.format,
2202 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2203 offloadInfo.has_video);
2204
2205 // Check if offload has been disabled
2206 char propValue[PROPERTY_VALUE_MAX];
2207 if (property_get("audio.offload.disable", propValue, "0")) {
2208 if (atoi(propValue) != 0) {
2209 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2210 return false;
2211 }
2212 }
2213
2214 // Check if stream type is music, then only allow offload as of now.
2215 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2216 {
2217 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2218 return false;
2219 }
2220
2221 //TODO: enable audio offloading with video when ready
2222 if (offloadInfo.has_video)
2223 {
2224 ALOGV("isOffloadSupported: has_video == true, returning false");
2225 return false;
2226 }
2227
2228 //If duration is less than minimum value defined in property, return false
2229 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2230 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2231 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2232 return false;
2233 }
2234 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2235 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2236 return false;
2237 }
2238
2239 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2240 // creating an offloaded track and tearing it down immediately after start when audioflinger
2241 // detects there is an active non offloadable effect.
2242 // FIXME: We should check the audio session here but we do not have it in this context.
2243 // This may prevent offloading in rare situations where effects are left active by apps
2244 // in the background.
2245 if (isNonOffloadableEffectEnabled()) {
2246 return false;
2247 }
2248
2249 // See if there is a profile to support this.
2250 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002251 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002252 offloadInfo.sample_rate,
2253 offloadInfo.format,
2254 offloadInfo.channel_mask,
2255 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002256 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2257 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002258}
2259
Eric Laurent6a94d692014-05-20 11:18:06 -07002260status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2261 audio_port_type_t type,
2262 unsigned int *num_ports,
2263 struct audio_port *ports,
2264 unsigned int *generation)
2265{
2266 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2267 generation == NULL) {
2268 return BAD_VALUE;
2269 }
2270 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2271 if (ports == NULL) {
2272 *num_ports = 0;
2273 }
2274
2275 size_t portsWritten = 0;
2276 size_t portsMax = *num_ports;
2277 *num_ports = 0;
2278 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2279 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2280 for (size_t i = 0;
2281 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2282 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2283 }
2284 *num_ports += mAvailableOutputDevices.size();
2285 }
2286 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2287 for (size_t i = 0;
2288 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2289 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2290 }
2291 *num_ports += mAvailableInputDevices.size();
2292 }
2293 }
2294 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2295 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2296 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2297 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2298 }
2299 *num_ports += mInputs.size();
2300 }
2301 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002302 size_t numOutputs = 0;
2303 for (size_t i = 0; i < mOutputs.size(); i++) {
2304 if (!mOutputs[i]->isDuplicated()) {
2305 numOutputs++;
2306 if (portsWritten < portsMax) {
2307 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2308 }
2309 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002310 }
Eric Laurent84c70242014-06-23 08:46:27 -07002311 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002312 }
2313 }
2314 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002315 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002316 return NO_ERROR;
2317}
2318
2319status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2320{
2321 return NO_ERROR;
2322}
2323
Eric Laurent1f2f2232014-06-02 12:01:23 -07002324sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002325 audio_port_handle_t id) const
2326{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002327 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002328 for (size_t i = 0; i < mOutputs.size(); i++) {
2329 outputDesc = mOutputs.valueAt(i);
2330 if (outputDesc->mId == id) {
2331 break;
2332 }
2333 }
2334 return outputDesc;
2335}
2336
Eric Laurent1f2f2232014-06-02 12:01:23 -07002337sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002338 audio_port_handle_t id) const
2339{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002340 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002341 for (size_t i = 0; i < mInputs.size(); i++) {
2342 inputDesc = mInputs.valueAt(i);
2343 if (inputDesc->mId == id) {
2344 break;
2345 }
2346 }
2347 return inputDesc;
2348}
2349
Eric Laurent1f2f2232014-06-02 12:01:23 -07002350sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2351 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002352{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002353 sp <HwModule> module;
2354
Eric Laurent6a94d692014-05-20 11:18:06 -07002355 for (size_t i = 0; i < mHwModules.size(); i++) {
2356 if (mHwModules[i]->mHandle == 0) {
2357 continue;
2358 }
2359 if (audio_is_output_device(device)) {
2360 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2361 {
2362 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2363 return mHwModules[i];
2364 }
2365 }
2366 } else {
2367 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2368 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2369 device & ~AUDIO_DEVICE_BIT_IN) {
2370 return mHwModules[i];
2371 }
2372 }
2373 }
2374 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002375 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002376}
2377
Eric Laurent1f2f2232014-06-02 12:01:23 -07002378sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002379{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002380 sp <HwModule> module;
2381
Eric Laurent1afeecb2014-05-14 08:52:28 -07002382 for (size_t i = 0; i < mHwModules.size(); i++)
2383 {
2384 if (strcmp(mHwModules[i]->mName, name) == 0) {
2385 return mHwModules[i];
2386 }
2387 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002388 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002389}
2390
Eric Laurentc2730ba2014-07-20 15:47:07 -07002391audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2392{
2393 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2394 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2395 return devices & mAvailableOutputDevices.types();
2396}
2397
2398audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2399{
2400 audio_module_handle_t primaryHandle =
2401 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2402 audio_devices_t devices = AUDIO_DEVICE_NONE;
2403 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2404 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2405 devices |= mAvailableInputDevices[i]->mDeviceType;
2406 }
2407 }
2408 return devices;
2409}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002410
Eric Laurent6a94d692014-05-20 11:18:06 -07002411status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2412 audio_patch_handle_t *handle,
2413 uid_t uid)
2414{
2415 ALOGV("createAudioPatch()");
2416
2417 if (handle == NULL || patch == NULL) {
2418 return BAD_VALUE;
2419 }
2420 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2421
Eric Laurent874c42872014-08-08 15:13:39 -07002422 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2423 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2424 return BAD_VALUE;
2425 }
2426 // only one source per audio patch supported for now
2427 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002428 return INVALID_OPERATION;
2429 }
Eric Laurent874c42872014-08-08 15:13:39 -07002430
2431 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002432 return INVALID_OPERATION;
2433 }
Eric Laurent874c42872014-08-08 15:13:39 -07002434 for (size_t i = 0; i < patch->num_sinks; i++) {
2435 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2436 return INVALID_OPERATION;
2437 }
2438 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002439
2440 sp<AudioPatch> patchDesc;
2441 ssize_t index = mAudioPatches.indexOfKey(*handle);
2442
Eric Laurent6a94d692014-05-20 11:18:06 -07002443 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2444 patch->sources[0].role,
2445 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002446#if LOG_NDEBUG == 0
2447 for (size_t i = 0; i < patch->num_sinks; i++) {
2448 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2449 patch->sinks[i].role,
2450 patch->sinks[i].type);
2451 }
2452#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002453
2454 if (index >= 0) {
2455 patchDesc = mAudioPatches.valueAt(index);
2456 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2457 mUidCached, patchDesc->mUid, uid);
2458 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2459 return INVALID_OPERATION;
2460 }
2461 } else {
2462 *handle = 0;
2463 }
2464
2465 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002466 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002467 if (outputDesc == NULL) {
2468 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2469 return BAD_VALUE;
2470 }
Eric Laurent84c70242014-06-23 08:46:27 -07002471 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2472 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002473 if (patchDesc != 0) {
2474 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2475 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2476 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2477 return BAD_VALUE;
2478 }
2479 }
Eric Laurent874c42872014-08-08 15:13:39 -07002480 DeviceVector devices;
2481 for (size_t i = 0; i < patch->num_sinks; i++) {
2482 // Only support mix to devices connection
2483 // TODO add support for mix to mix connection
2484 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2485 ALOGV("createAudioPatch() source mix but sink is not a device");
2486 return INVALID_OPERATION;
2487 }
2488 sp<DeviceDescriptor> devDesc =
2489 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2490 if (devDesc == 0) {
2491 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2492 return BAD_VALUE;
2493 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002494
Eric Laurent874c42872014-08-08 15:13:39 -07002495 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002496 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002497 patch->sources[0].sample_rate,
2498 NULL, // updatedSamplingRate
2499 patch->sources[0].format,
2500 patch->sources[0].channel_mask,
2501 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2502 ALOGV("createAudioPatch() profile not supported for device %08x",
2503 devDesc->mDeviceType);
2504 return INVALID_OPERATION;
2505 }
2506 devices.add(devDesc);
2507 }
2508 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002509 return INVALID_OPERATION;
2510 }
Eric Laurent874c42872014-08-08 15:13:39 -07002511
Eric Laurent6a94d692014-05-20 11:18:06 -07002512 // TODO: reconfigure output format and channels here
2513 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002514 devices.types(), outputDesc->mIoHandle);
2515 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002516 index = mAudioPatches.indexOfKey(*handle);
2517 if (index >= 0) {
2518 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2519 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2520 }
2521 patchDesc = mAudioPatches.valueAt(index);
2522 patchDesc->mUid = uid;
2523 ALOGV("createAudioPatch() success");
2524 } else {
2525 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2526 return INVALID_OPERATION;
2527 }
2528 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2529 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2530 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002531 // only one sink supported when connecting an input device to a mix
2532 if (patch->num_sinks > 1) {
2533 return INVALID_OPERATION;
2534 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002535 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002536 if (inputDesc == NULL) {
2537 return BAD_VALUE;
2538 }
2539 if (patchDesc != 0) {
2540 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2541 return BAD_VALUE;
2542 }
2543 }
2544 sp<DeviceDescriptor> devDesc =
2545 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2546 if (devDesc == 0) {
2547 return BAD_VALUE;
2548 }
2549
Eric Laurent84c70242014-06-23 08:46:27 -07002550 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002551 devDesc->mAddress,
2552 patch->sinks[0].sample_rate,
2553 NULL, /*updatedSampleRate*/
2554 patch->sinks[0].format,
2555 patch->sinks[0].channel_mask,
2556 // FIXME for the parameter type,
2557 // and the NONE
2558 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002559 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002560 return INVALID_OPERATION;
2561 }
2562 // TODO: reconfigure output format and channels here
2563 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002564 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002565 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002566 index = mAudioPatches.indexOfKey(*handle);
2567 if (index >= 0) {
2568 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2569 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2570 }
2571 patchDesc = mAudioPatches.valueAt(index);
2572 patchDesc->mUid = uid;
2573 ALOGV("createAudioPatch() success");
2574 } else {
2575 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2576 return INVALID_OPERATION;
2577 }
2578 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2579 // device to device connection
2580 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002581 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002582 return BAD_VALUE;
2583 }
2584 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002585 sp<DeviceDescriptor> srcDeviceDesc =
2586 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002587 if (srcDeviceDesc == 0) {
2588 return BAD_VALUE;
2589 }
Eric Laurent874c42872014-08-08 15:13:39 -07002590
Eric Laurent6a94d692014-05-20 11:18:06 -07002591 //update source and sink with our own data as the data passed in the patch may
2592 // be incomplete.
2593 struct audio_patch newPatch = *patch;
2594 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002595
Eric Laurent874c42872014-08-08 15:13:39 -07002596 for (size_t i = 0; i < patch->num_sinks; i++) {
2597 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2598 ALOGV("createAudioPatch() source device but one sink is not a device");
2599 return INVALID_OPERATION;
2600 }
2601
2602 sp<DeviceDescriptor> sinkDeviceDesc =
2603 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2604 if (sinkDeviceDesc == 0) {
2605 return BAD_VALUE;
2606 }
2607 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2608
2609 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2610 // only one sink supported when connected devices across HW modules
2611 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002612 return INVALID_OPERATION;
2613 }
Eric Laurent874c42872014-08-08 15:13:39 -07002614 SortedVector<audio_io_handle_t> outputs =
2615 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2616 mOutputs);
2617 // if the sink device is reachable via an opened output stream, request to go via
2618 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002619 audio_io_handle_t output = selectOutput(outputs,
2620 AUDIO_OUTPUT_FLAG_NONE,
2621 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002622 if (output != AUDIO_IO_HANDLE_NONE) {
2623 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2624 if (outputDesc->isDuplicated()) {
2625 return INVALID_OPERATION;
2626 }
2627 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2628 newPatch.num_sources = 2;
2629 }
Eric Laurent83b88082014-06-20 18:31:16 -07002630 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002631 }
2632 // TODO: check from routing capabilities in config file and other conflicting patches
2633
2634 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2635 if (index >= 0) {
2636 afPatchHandle = patchDesc->mAfPatchHandle;
2637 }
2638
2639 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2640 &afPatchHandle,
2641 0);
2642 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2643 status, afPatchHandle);
2644 if (status == NO_ERROR) {
2645 if (index < 0) {
2646 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2647 &newPatch, uid);
2648 addAudioPatch(patchDesc->mHandle, patchDesc);
2649 } else {
2650 patchDesc->mPatch = newPatch;
2651 }
2652 patchDesc->mAfPatchHandle = afPatchHandle;
2653 *handle = patchDesc->mHandle;
2654 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002655 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002656 } else {
2657 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2658 status);
2659 return INVALID_OPERATION;
2660 }
2661 } else {
2662 return BAD_VALUE;
2663 }
2664 } else {
2665 return BAD_VALUE;
2666 }
2667 return NO_ERROR;
2668}
2669
2670status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2671 uid_t uid)
2672{
2673 ALOGV("releaseAudioPatch() patch %d", handle);
2674
2675 ssize_t index = mAudioPatches.indexOfKey(handle);
2676
2677 if (index < 0) {
2678 return BAD_VALUE;
2679 }
2680 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2681 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2682 mUidCached, patchDesc->mUid, uid);
2683 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2684 return INVALID_OPERATION;
2685 }
2686
2687 struct audio_patch *patch = &patchDesc->mPatch;
2688 patchDesc->mUid = mUidCached;
2689 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002690 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002691 if (outputDesc == NULL) {
2692 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2693 return BAD_VALUE;
2694 }
2695
2696 setOutputDevice(outputDesc->mIoHandle,
2697 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2698 true,
2699 0,
2700 NULL);
2701 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2702 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002703 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002704 if (inputDesc == NULL) {
2705 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2706 return BAD_VALUE;
2707 }
2708 setInputDevice(inputDesc->mIoHandle,
2709 getNewInputDevice(inputDesc->mIoHandle),
2710 true,
2711 NULL);
2712 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2713 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2714 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2715 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2716 status, patchDesc->mAfPatchHandle);
2717 removeAudioPatch(patchDesc->mHandle);
2718 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002719 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002720 } else {
2721 return BAD_VALUE;
2722 }
2723 } else {
2724 return BAD_VALUE;
2725 }
2726 return NO_ERROR;
2727}
2728
2729status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2730 struct audio_patch *patches,
2731 unsigned int *generation)
2732{
2733 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2734 generation == NULL) {
2735 return BAD_VALUE;
2736 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002737 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002738 *num_patches, patches, mAudioPatches.size());
2739 if (patches == NULL) {
2740 *num_patches = 0;
2741 }
2742
2743 size_t patchesWritten = 0;
2744 size_t patchesMax = *num_patches;
2745 for (size_t i = 0;
2746 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2747 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2748 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002749 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002750 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2751 }
2752 *num_patches = mAudioPatches.size();
2753
2754 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002755 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002756 return NO_ERROR;
2757}
2758
Eric Laurente1715a42014-05-20 11:30:42 -07002759status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002760{
Eric Laurente1715a42014-05-20 11:30:42 -07002761 ALOGV("setAudioPortConfig()");
2762
2763 if (config == NULL) {
2764 return BAD_VALUE;
2765 }
2766 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2767 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002768 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2769 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002770 }
2771
Eric Laurenta121f902014-06-03 13:32:54 -07002772 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002773 if (config->type == AUDIO_PORT_TYPE_MIX) {
2774 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002775 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002776 if (outputDesc == NULL) {
2777 return BAD_VALUE;
2778 }
Eric Laurent84c70242014-06-23 08:46:27 -07002779 ALOG_ASSERT(!outputDesc->isDuplicated(),
2780 "setAudioPortConfig() called on duplicated output %d",
2781 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002782 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002783 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002784 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002785 if (inputDesc == NULL) {
2786 return BAD_VALUE;
2787 }
Eric Laurenta121f902014-06-03 13:32:54 -07002788 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002789 } else {
2790 return BAD_VALUE;
2791 }
2792 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2793 sp<DeviceDescriptor> deviceDesc;
2794 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2795 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2796 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2797 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2798 } else {
2799 return BAD_VALUE;
2800 }
2801 if (deviceDesc == NULL) {
2802 return BAD_VALUE;
2803 }
Eric Laurenta121f902014-06-03 13:32:54 -07002804 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002805 } else {
2806 return BAD_VALUE;
2807 }
2808
Eric Laurenta121f902014-06-03 13:32:54 -07002809 struct audio_port_config backupConfig;
2810 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2811 if (status == NO_ERROR) {
2812 struct audio_port_config newConfig;
2813 audioPortConfig->toAudioPortConfig(&newConfig, config);
2814 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002815 }
Eric Laurenta121f902014-06-03 13:32:54 -07002816 if (status != NO_ERROR) {
2817 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002818 }
Eric Laurente1715a42014-05-20 11:30:42 -07002819
2820 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002821}
2822
2823void AudioPolicyManager::clearAudioPatches(uid_t uid)
2824{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002825 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002826 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2827 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002828 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002829 }
2830 }
2831}
2832
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002833status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2834 audio_io_handle_t *ioHandle,
2835 audio_devices_t *device)
2836{
2837 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2838 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2839 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2840
2841 mSoundTriggerSessions.add(*session, *ioHandle);
2842
2843 return NO_ERROR;
2844}
2845
2846status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2847{
2848 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2849 if (index < 0) {
2850 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2851 return BAD_VALUE;
2852 }
2853
2854 mSoundTriggerSessions.removeItem(session);
2855 return NO_ERROR;
2856}
2857
Eric Laurent6a94d692014-05-20 11:18:06 -07002858status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2859 const sp<AudioPatch>& patch)
2860{
2861 ssize_t index = mAudioPatches.indexOfKey(handle);
2862
2863 if (index >= 0) {
2864 ALOGW("addAudioPatch() patch %d already in", handle);
2865 return ALREADY_EXISTS;
2866 }
2867 mAudioPatches.add(handle, patch);
2868 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2869 "sink handle %d",
2870 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2871 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2872 return NO_ERROR;
2873}
2874
2875status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2876{
2877 ssize_t index = mAudioPatches.indexOfKey(handle);
2878
2879 if (index < 0) {
2880 ALOGW("removeAudioPatch() patch %d not in", handle);
2881 return ALREADY_EXISTS;
2882 }
2883 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2884 mAudioPatches.valueAt(index)->mAfPatchHandle);
2885 mAudioPatches.removeItemsAt(index);
2886 return NO_ERROR;
2887}
2888
Eric Laurente552edb2014-03-10 17:42:56 -07002889// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002890// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002891// ----------------------------------------------------------------------------
2892
Eric Laurent3a4311c2014-03-17 12:00:47 -07002893uint32_t AudioPolicyManager::nextUniqueId()
2894{
2895 return android_atomic_inc(&mNextUniqueId);
2896}
2897
Eric Laurent6a94d692014-05-20 11:18:06 -07002898uint32_t AudioPolicyManager::nextAudioPortGeneration()
2899{
2900 return android_atomic_inc(&mAudioPortGeneration);
2901}
2902
Eric Laurente0720872014-03-11 09:30:41 -07002903AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002904 :
2905#ifdef AUDIO_POLICY_TEST
2906 Thread(false),
2907#endif //AUDIO_POLICY_TEST
2908 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002909 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002910 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2911 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002912 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002913 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002914 mAudioPortGeneration(1),
2915 mBeaconMuteRefCount(0),
2916 mBeaconPlayingRefCount(0),
2917 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07002918{
Eric Laurent6a94d692014-05-20 11:18:06 -07002919 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002920 mpClientInterface = clientInterface;
2921
Eric Laurent3b73df72014-03-11 09:06:29 -07002922 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2923 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002924 }
2925
Eric Laurent1afeecb2014-05-14 08:52:28 -07002926 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002927 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2928 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2929 ALOGE("could not load audio policy configuration file, setting defaults");
2930 defaultAudioPolicyConfig();
2931 }
2932 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002933 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002934
2935 // must be done after reading the policy
2936 initializeVolumeCurves();
2937
2938 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002939 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2940 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002941 for (size_t i = 0; i < mHwModules.size(); i++) {
2942 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2943 if (mHwModules[i]->mHandle == 0) {
2944 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2945 continue;
2946 }
2947 // open all output streams needed to access attached devices
2948 // except for direct output streams that are only opened when they are actually
2949 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002950 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002951 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2952 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002953 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002954
Eric Laurent3a4311c2014-03-17 12:00:47 -07002955 if (outProfile->mSupportedDevices.isEmpty()) {
2956 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2957 continue;
2958 }
2959
Eric Laurentd78f1532014-09-16 16:38:20 -07002960 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
2961 continue;
2962 }
Eric Laurent83b88082014-06-20 18:31:16 -07002963 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2964 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2965 profileType = mDefaultOutputDevice->mDeviceType;
2966 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07002967 // chose first device present in mSupportedDevices also part of
2968 // outputDeviceTypes
2969 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2970 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
2971 if ((profileType & outputDeviceTypes) != 0) {
2972 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002973 }
Eric Laurente552edb2014-03-10 17:42:56 -07002974 }
2975 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002976 if ((profileType & outputDeviceTypes) == 0) {
2977 continue;
2978 }
2979 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
2980
2981 outputDesc->mDevice = profileType;
2982 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2983 config.sample_rate = outputDesc->mSamplingRate;
2984 config.channel_mask = outputDesc->mChannelMask;
2985 config.format = outputDesc->mFormat;
2986 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2987 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2988 &output,
2989 &config,
2990 &outputDesc->mDevice,
2991 String8(""),
2992 &outputDesc->mLatency,
2993 outputDesc->mFlags);
2994
2995 if (status != NO_ERROR) {
2996 ALOGW("Cannot open output stream for device %08x on hw module %s",
2997 outputDesc->mDevice,
2998 mHwModules[i]->mName);
2999 } else {
3000 outputDesc->mSamplingRate = config.sample_rate;
3001 outputDesc->mChannelMask = config.channel_mask;
3002 outputDesc->mFormat = config.format;
3003
3004 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3005 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
3006 ssize_t index =
3007 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
3008 // give a valid ID to an attached device once confirmed it is reachable
3009 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
3010 mAvailableOutputDevices[index]->mId = nextUniqueId();
3011 mAvailableOutputDevices[index]->mModule = mHwModules[i];
3012 }
3013 }
3014 if (mPrimaryOutput == 0 &&
3015 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
3016 mPrimaryOutput = output;
3017 }
3018 addOutput(output, outputDesc);
3019 setOutputDevice(output,
3020 outputDesc->mDevice,
3021 true);
3022 }
Eric Laurente552edb2014-03-10 17:42:56 -07003023 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003024 // open input streams needed to access attached devices to validate
3025 // mAvailableInputDevices list
3026 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3027 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003028 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003029
Eric Laurent3a4311c2014-03-17 12:00:47 -07003030 if (inProfile->mSupportedDevices.isEmpty()) {
3031 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
3032 continue;
3033 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003034 // chose first device present in mSupportedDevices also part of
3035 // inputDeviceTypes
3036 audio_devices_t profileType = AUDIO_DEVICE_NONE;
3037 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3038 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
3039 if (profileType & inputDeviceTypes) {
3040 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003041 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003042 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003043 if ((profileType & inputDeviceTypes) == 0) {
3044 continue;
3045 }
3046 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
3047
3048 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
3049 inputDesc->mDevice = profileType;
3050
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003051 // find the address
3052 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3053 // the inputs vector must be of size 1, but we don't want to crash here
3054 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3055 : String8("");
3056 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3057 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3058
Eric Laurentd78f1532014-09-16 16:38:20 -07003059 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3060 config.sample_rate = inputDesc->mSamplingRate;
3061 config.channel_mask = inputDesc->mChannelMask;
3062 config.format = inputDesc->mFormat;
3063 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3064 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
3065 &input,
3066 &config,
3067 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003068 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003069 AUDIO_SOURCE_MIC,
3070 AUDIO_INPUT_FLAG_NONE);
3071
3072 if (status == NO_ERROR) {
3073 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3074 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
3075 ssize_t index =
3076 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
3077 // give a valid ID to an attached device once confirmed it is reachable
3078 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
3079 mAvailableInputDevices[index]->mId = nextUniqueId();
3080 mAvailableInputDevices[index]->mModule = mHwModules[i];
3081 }
3082 }
3083 mpClientInterface->closeInput(input);
3084 } else {
3085 ALOGW("Cannot open input stream for device %08x on hw module %s",
3086 inputDesc->mDevice,
3087 mHwModules[i]->mName);
3088 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003089 }
3090 }
3091 // make sure all attached devices have been allocated a unique ID
3092 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
3093 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003094 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003095 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3096 continue;
3097 }
3098 i++;
3099 }
3100 for (size_t i = 0; i < mAvailableInputDevices.size();) {
3101 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003102 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003103 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3104 continue;
3105 }
3106 i++;
3107 }
3108 // make sure default device is reachable
3109 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003110 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003111 }
Eric Laurente552edb2014-03-10 17:42:56 -07003112
3113 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3114
3115 updateDevicesAndOutputs();
3116
3117#ifdef AUDIO_POLICY_TEST
3118 if (mPrimaryOutput != 0) {
3119 AudioParameter outputCmd = AudioParameter();
3120 outputCmd.addInt(String8("set_id"), 0);
3121 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3122
3123 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3124 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003125 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3126 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003127 mTestLatencyMs = 0;
3128 mCurOutput = 0;
3129 mDirectOutput = false;
3130 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3131 mTestOutputs[i] = 0;
3132 }
3133
3134 const size_t SIZE = 256;
3135 char buffer[SIZE];
3136 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3137 run(buffer, ANDROID_PRIORITY_AUDIO);
3138 }
3139#endif //AUDIO_POLICY_TEST
3140}
3141
Eric Laurente0720872014-03-11 09:30:41 -07003142AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003143{
3144#ifdef AUDIO_POLICY_TEST
3145 exit();
3146#endif //AUDIO_POLICY_TEST
3147 for (size_t i = 0; i < mOutputs.size(); i++) {
3148 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003149 }
3150 for (size_t i = 0; i < mInputs.size(); i++) {
3151 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003152 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003153 mAvailableOutputDevices.clear();
3154 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003155 mOutputs.clear();
3156 mInputs.clear();
3157 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003158}
3159
Eric Laurente0720872014-03-11 09:30:41 -07003160status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003161{
3162 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
3163}
3164
3165#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003166bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003167{
3168 ALOGV("entering threadLoop()");
3169 while (!exitPending())
3170 {
3171 String8 command;
3172 int valueInt;
3173 String8 value;
3174
3175 Mutex::Autolock _l(mLock);
3176 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3177
3178 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3179 AudioParameter param = AudioParameter(command);
3180
3181 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3182 valueInt != 0) {
3183 ALOGV("Test command %s received", command.string());
3184 String8 target;
3185 if (param.get(String8("target"), target) != NO_ERROR) {
3186 target = "Manager";
3187 }
3188 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3189 param.remove(String8("test_cmd_policy_output"));
3190 mCurOutput = valueInt;
3191 }
3192 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3193 param.remove(String8("test_cmd_policy_direct"));
3194 if (value == "false") {
3195 mDirectOutput = false;
3196 } else if (value == "true") {
3197 mDirectOutput = true;
3198 }
3199 }
3200 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3201 param.remove(String8("test_cmd_policy_input"));
3202 mTestInput = valueInt;
3203 }
3204
3205 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3206 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003207 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003208 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003209 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003210 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003211 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003212 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003213 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003214 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003215 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003216 if (target == "Manager") {
3217 mTestFormat = format;
3218 } else if (mTestOutputs[mCurOutput] != 0) {
3219 AudioParameter outputParam = AudioParameter();
3220 outputParam.addInt(String8("format"), format);
3221 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3222 }
3223 }
3224 }
3225 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3226 param.remove(String8("test_cmd_policy_channels"));
3227 int channels = 0;
3228
3229 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003230 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003231 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003232 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003233 }
3234 if (channels != 0) {
3235 if (target == "Manager") {
3236 mTestChannels = channels;
3237 } else if (mTestOutputs[mCurOutput] != 0) {
3238 AudioParameter outputParam = AudioParameter();
3239 outputParam.addInt(String8("channels"), channels);
3240 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3241 }
3242 }
3243 }
3244 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3245 param.remove(String8("test_cmd_policy_sampleRate"));
3246 if (valueInt >= 0 && valueInt <= 96000) {
3247 int samplingRate = valueInt;
3248 if (target == "Manager") {
3249 mTestSamplingRate = samplingRate;
3250 } else if (mTestOutputs[mCurOutput] != 0) {
3251 AudioParameter outputParam = AudioParameter();
3252 outputParam.addInt(String8("sampling_rate"), samplingRate);
3253 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3254 }
3255 }
3256 }
3257
3258 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3259 param.remove(String8("test_cmd_policy_reopen"));
3260
Eric Laurent1f2f2232014-06-02 12:01:23 -07003261 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003262 mpClientInterface->closeOutput(mPrimaryOutput);
3263
3264 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3265
Eric Laurente552edb2014-03-10 17:42:56 -07003266 mOutputs.removeItem(mPrimaryOutput);
3267
Eric Laurent1f2f2232014-06-02 12:01:23 -07003268 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003269 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003270 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3271 config.sample_rate = outputDesc->mSamplingRate;
3272 config.channel_mask = outputDesc->mChannelMask;
3273 config.format = outputDesc->mFormat;
3274 status_t status = mpClientInterface->openOutput(moduleHandle,
3275 &mPrimaryOutput,
3276 &config,
3277 &outputDesc->mDevice,
3278 String8(""),
3279 &outputDesc->mLatency,
3280 outputDesc->mFlags);
3281 if (status != NO_ERROR) {
3282 ALOGE("Failed to reopen hardware output stream, "
3283 "samplingRate: %d, format %d, channels %d",
3284 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003285 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003286 outputDesc->mSamplingRate = config.sample_rate;
3287 outputDesc->mChannelMask = config.channel_mask;
3288 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003289 AudioParameter outputCmd = AudioParameter();
3290 outputCmd.addInt(String8("set_id"), 0);
3291 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3292 addOutput(mPrimaryOutput, outputDesc);
3293 }
3294 }
3295
3296
3297 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3298 }
3299 }
3300 return false;
3301}
3302
Eric Laurente0720872014-03-11 09:30:41 -07003303void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003304{
3305 {
3306 AutoMutex _l(mLock);
3307 requestExit();
3308 mWaitWorkCV.signal();
3309 }
3310 requestExitAndWait();
3311}
3312
Eric Laurente0720872014-03-11 09:30:41 -07003313int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003314{
3315 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3316 if (output == mTestOutputs[i]) return i;
3317 }
3318 return 0;
3319}
3320#endif //AUDIO_POLICY_TEST
3321
3322// ---
3323
Eric Laurent1f2f2232014-06-02 12:01:23 -07003324void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003325{
Eric Laurent1c333e22014-05-20 10:48:17 -07003326 outputDesc->mIoHandle = output;
3327 outputDesc->mId = nextUniqueId();
3328 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003329 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003330}
3331
Eric Laurent1f2f2232014-06-02 12:01:23 -07003332void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003333{
Eric Laurent1c333e22014-05-20 10:48:17 -07003334 inputDesc->mIoHandle = input;
3335 inputDesc->mId = nextUniqueId();
3336 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003337 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003338}
Eric Laurente552edb2014-03-10 17:42:56 -07003339
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003340void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3341 const String8 address /*in*/,
3342 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3343 // look for a match on the given address on the addresses of the outputs:
3344 // find the address by finding the patch that maps to this output
3345 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3346 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3347 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3348 if (patchIdx >= 0) {
3349 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3350 const int numSinks = patchDesc->mPatch.num_sinks;
3351 for (ssize_t j=0; j < numSinks; j++) {
3352 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3353 const char* patchAddr =
3354 patchDesc->mPatch.sinks[j].ext.device.address;
3355 if (strncmp(patchAddr,
3356 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003357 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003358 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3359 outputs.add(desc->mIoHandle);
3360 break;
3361 }
3362 }
3363 }
3364 }
3365}
3366
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003367status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003368 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003369 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003370 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003371{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003372 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003373 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003374 // erase all current sample rates, formats and channel masks
3375 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003376
Eric Laurent3b73df72014-03-11 09:06:29 -07003377 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003378 // first list already open outputs that can be routed to this device
3379 for (size_t i = 0; i < mOutputs.size(); i++) {
3380 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003381 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003382 if (!deviceDistinguishesOnAddress(device)) {
3383 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3384 outputs.add(mOutputs.keyAt(i));
3385 } else {
3386 ALOGV(" checking address match due to device 0x%x", device);
3387 findIoHandlesByAddress(desc, address, outputs);
3388 }
Eric Laurente552edb2014-03-10 17:42:56 -07003389 }
3390 }
3391 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003392 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003393 for (size_t i = 0; i < mHwModules.size(); i++)
3394 {
3395 if (mHwModules[i]->mHandle == 0) {
3396 continue;
3397 }
3398 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3399 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003400 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3401 if (profile->mSupportedDevices.types() & device) {
3402 if (!deviceDistinguishesOnAddress(device) ||
3403 address == profile->mSupportedDevices[0]->mAddress) {
3404 profiles.add(profile);
3405 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3406 }
Eric Laurente552edb2014-03-10 17:42:56 -07003407 }
3408 }
3409 }
3410
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003411 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3412
Eric Laurente552edb2014-03-10 17:42:56 -07003413 if (profiles.isEmpty() && outputs.isEmpty()) {
3414 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3415 return BAD_VALUE;
3416 }
3417
3418 // open outputs for matching profiles if needed. Direct outputs are also opened to
3419 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3420 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003421 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003422
3423 // nothing to do if one output is already opened for this profile
3424 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003425 for (j = 0; j < outputs.size(); j++) {
3426 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003427 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003428 // matching profile: save the sample rates, format and channel masks supported
3429 // by the profile in our device descriptor
3430 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003431 break;
3432 }
3433 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003434 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003435 continue;
3436 }
3437
Eric Laurent83b88082014-06-20 18:31:16 -07003438 ALOGV("opening output for device %08x with params %s profile %p",
3439 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003440 desc = new AudioOutputDescriptor(profile);
3441 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003442 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3443 config.sample_rate = desc->mSamplingRate;
3444 config.channel_mask = desc->mChannelMask;
3445 config.format = desc->mFormat;
3446 config.offload_info.sample_rate = desc->mSamplingRate;
3447 config.offload_info.channel_mask = desc->mChannelMask;
3448 config.offload_info.format = desc->mFormat;
3449 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3450 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3451 &output,
3452 &config,
3453 &desc->mDevice,
3454 address,
3455 &desc->mLatency,
3456 desc->mFlags);
3457 if (status == NO_ERROR) {
3458 desc->mSamplingRate = config.sample_rate;
3459 desc->mChannelMask = config.channel_mask;
3460 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003461
Eric Laurentd4692962014-05-05 18:13:44 -07003462 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003463 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003464 char *param = audio_device_address_to_parameter(device, address);
3465 mpClientInterface->setParameters(output, String8(param));
3466 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003467 }
3468
Eric Laurentd4692962014-05-05 18:13:44 -07003469 // Here is where we step through and resolve any "dynamic" fields
3470 String8 reply;
3471 char *value;
3472 if (profile->mSamplingRates[0] == 0) {
3473 reply = mpClientInterface->getParameters(output,
3474 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003475 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003476 reply.string());
3477 value = strpbrk((char *)reply.string(), "=");
3478 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003479 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003480 }
Eric Laurentd4692962014-05-05 18:13:44 -07003481 }
3482 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3483 reply = mpClientInterface->getParameters(output,
3484 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003485 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003486 reply.string());
3487 value = strpbrk((char *)reply.string(), "=");
3488 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003489 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003490 }
Eric Laurentd4692962014-05-05 18:13:44 -07003491 }
3492 if (profile->mChannelMasks[0] == 0) {
3493 reply = mpClientInterface->getParameters(output,
3494 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003495 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003496 reply.string());
3497 value = strpbrk((char *)reply.string(), "=");
3498 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003499 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003500 }
Eric Laurentd4692962014-05-05 18:13:44 -07003501 }
3502 if (((profile->mSamplingRates[0] == 0) &&
3503 (profile->mSamplingRates.size() < 2)) ||
3504 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3505 (profile->mFormats.size() < 2)) ||
3506 ((profile->mChannelMasks[0] == 0) &&
3507 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003508 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003509 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003510 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003511 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3512 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003513 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003514 config.sample_rate = profile->pickSamplingRate();
3515 config.channel_mask = profile->pickChannelMask();
3516 config.format = profile->pickFormat();
3517 config.offload_info.sample_rate = config.sample_rate;
3518 config.offload_info.channel_mask = config.channel_mask;
3519 config.offload_info.format = config.format;
3520 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3521 &output,
3522 &config,
3523 &desc->mDevice,
3524 address,
3525 &desc->mLatency,
3526 desc->mFlags);
3527 if (status == NO_ERROR) {
3528 desc->mSamplingRate = config.sample_rate;
3529 desc->mChannelMask = config.channel_mask;
3530 desc->mFormat = config.format;
3531 } else {
3532 output = AUDIO_IO_HANDLE_NONE;
3533 }
Eric Laurentd4692962014-05-05 18:13:44 -07003534 }
3535
Eric Laurentcf2c0212014-07-25 16:20:43 -07003536 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003537 addOutput(output, desc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003538 if (deviceDistinguishesOnAddress(device) && address != "0") {
3539 ssize_t index = mPolicyMixes.indexOfKey(address);
3540 if (index >= 0) {
3541 mPolicyMixes[index]->mOutput = desc;
3542 } else {
3543 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3544 address.string());
3545 }
3546 }
Eric Laurentd4692962014-05-05 18:13:44 -07003547 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003548 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003549
Eric Laurentd4692962014-05-05 18:13:44 -07003550 // set initial stream volume for device
3551 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003552
Eric Laurentd4692962014-05-05 18:13:44 -07003553 //TODO: configure audio effect output stage here
3554
3555 // open a duplicating output thread for the new output and the primary output
3556 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3557 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003558 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003559 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003560 sp<AudioOutputDescriptor> dupOutputDesc =
3561 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003562 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3563 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3564 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3565 dupOutputDesc->mFormat = desc->mFormat;
3566 dupOutputDesc->mChannelMask = desc->mChannelMask;
3567 dupOutputDesc->mLatency = desc->mLatency;
3568 addOutput(duplicatedOutput, dupOutputDesc);
3569 applyStreamVolumes(duplicatedOutput, device, 0, true);
3570 } else {
3571 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3572 mPrimaryOutput, output);
3573 mpClientInterface->closeOutput(output);
3574 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003575 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003576 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003577 }
Eric Laurente552edb2014-03-10 17:42:56 -07003578 }
3579 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003580 } else {
3581 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003582 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003583 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003584 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003585 profiles.removeAt(profile_index);
3586 profile_index--;
3587 } else {
3588 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003589 devDesc->importAudioPort(profile);
3590
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003591 if (deviceDistinguishesOnAddress(device)) {
3592 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3593 device, address.string());
3594 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3595 NULL/*patch handle*/, address.string());
3596 }
Eric Laurente552edb2014-03-10 17:42:56 -07003597 ALOGV("checkOutputsForDevice(): adding output %d", output);
3598 }
3599 }
3600
3601 if (profiles.isEmpty()) {
3602 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3603 return BAD_VALUE;
3604 }
Eric Laurentd4692962014-05-05 18:13:44 -07003605 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003606 // check if one opened output is not needed any more after disconnecting one device
3607 for (size_t i = 0; i < mOutputs.size(); i++) {
3608 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003609 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003610 // exact match on device
3611 if (deviceDistinguishesOnAddress(device) &&
3612 (desc->mProfile->mSupportedDevices.types() == device)) {
3613 findIoHandlesByAddress(desc, address, outputs);
3614 } else if (!(desc->mProfile->mSupportedDevices.types()
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003615 & mAvailableOutputDevices.types())) {
3616 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3617 mOutputs.keyAt(i));
3618 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003619 }
Eric Laurente552edb2014-03-10 17:42:56 -07003620 }
3621 }
Eric Laurentd4692962014-05-05 18:13:44 -07003622 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003623 for (size_t i = 0; i < mHwModules.size(); i++)
3624 {
3625 if (mHwModules[i]->mHandle == 0) {
3626 continue;
3627 }
3628 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3629 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003630 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003631 if (profile->mSupportedDevices.types() & device) {
3632 ALOGV("checkOutputsForDevice(): "
3633 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003634 if (profile->mSamplingRates[0] == 0) {
3635 profile->mSamplingRates.clear();
3636 profile->mSamplingRates.add(0);
3637 }
3638 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3639 profile->mFormats.clear();
3640 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3641 }
3642 if (profile->mChannelMasks[0] == 0) {
3643 profile->mChannelMasks.clear();
3644 profile->mChannelMasks.add(0);
3645 }
3646 }
3647 }
3648 }
3649 }
3650 return NO_ERROR;
3651}
3652
Eric Laurentd4692962014-05-05 18:13:44 -07003653status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3654 audio_policy_dev_state_t state,
3655 SortedVector<audio_io_handle_t>& inputs,
3656 const String8 address)
3657{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003658 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003659 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3660 // first list already open inputs that can be routed to this device
3661 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3662 desc = mInputs.valueAt(input_index);
3663 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3664 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3665 inputs.add(mInputs.keyAt(input_index));
3666 }
3667 }
3668
3669 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003670 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003671 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3672 {
3673 if (mHwModules[module_idx]->mHandle == 0) {
3674 continue;
3675 }
3676 for (size_t profile_index = 0;
3677 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3678 profile_index++)
3679 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003680 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3681
3682 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3683 if (!deviceDistinguishesOnAddress(device) ||
3684 address == profile->mSupportedDevices[0]->mAddress) {
3685 profiles.add(profile);
3686 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3687 profile_index, module_idx);
3688 }
Eric Laurentd4692962014-05-05 18:13:44 -07003689 }
3690 }
3691 }
3692
3693 if (profiles.isEmpty() && inputs.isEmpty()) {
3694 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3695 return BAD_VALUE;
3696 }
3697
3698 // open inputs for matching profiles if needed. Direct inputs are also opened to
3699 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3700 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3701
Eric Laurent1c333e22014-05-20 10:48:17 -07003702 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003703 // nothing to do if one input is already opened for this profile
3704 size_t input_index;
3705 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3706 desc = mInputs.valueAt(input_index);
3707 if (desc->mProfile == profile) {
3708 break;
3709 }
3710 }
3711 if (input_index != mInputs.size()) {
3712 continue;
3713 }
3714
3715 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3716 desc = new AudioInputDescriptor(profile);
3717 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003718 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3719 config.sample_rate = desc->mSamplingRate;
3720 config.channel_mask = desc->mChannelMask;
3721 config.format = desc->mFormat;
3722 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3723 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3724 &input,
3725 &config,
3726 &desc->mDevice,
3727 address,
3728 AUDIO_SOURCE_MIC,
3729 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003730
Eric Laurentcf2c0212014-07-25 16:20:43 -07003731 if (status == NO_ERROR) {
3732 desc->mSamplingRate = config.sample_rate;
3733 desc->mChannelMask = config.channel_mask;
3734 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003735
Eric Laurentd4692962014-05-05 18:13:44 -07003736 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003737 char *param = audio_device_address_to_parameter(device, address);
3738 mpClientInterface->setParameters(input, String8(param));
3739 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003740 }
3741
3742 // Here is where we step through and resolve any "dynamic" fields
3743 String8 reply;
3744 char *value;
3745 if (profile->mSamplingRates[0] == 0) {
3746 reply = mpClientInterface->getParameters(input,
3747 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3748 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3749 reply.string());
3750 value = strpbrk((char *)reply.string(), "=");
3751 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003752 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003753 }
3754 }
3755 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3756 reply = mpClientInterface->getParameters(input,
3757 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3758 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3759 value = strpbrk((char *)reply.string(), "=");
3760 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003761 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003762 }
3763 }
3764 if (profile->mChannelMasks[0] == 0) {
3765 reply = mpClientInterface->getParameters(input,
3766 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3767 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3768 reply.string());
3769 value = strpbrk((char *)reply.string(), "=");
3770 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003771 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003772 }
3773 }
3774 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3775 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3776 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3777 ALOGW("checkInputsForDevice() direct input missing param");
3778 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003779 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003780 }
3781
3782 if (input != 0) {
3783 addInput(input, desc);
3784 }
3785 } // endif input != 0
3786
Eric Laurentcf2c0212014-07-25 16:20:43 -07003787 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003788 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003789 profiles.removeAt(profile_index);
3790 profile_index--;
3791 } else {
3792 inputs.add(input);
3793 ALOGV("checkInputsForDevice(): adding input %d", input);
3794 }
3795 } // end scan profiles
3796
3797 if (profiles.isEmpty()) {
3798 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3799 return BAD_VALUE;
3800 }
3801 } else {
3802 // Disconnect
3803 // check if one opened input is not needed any more after disconnecting one device
3804 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3805 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003806 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3807 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003808 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3809 mInputs.keyAt(input_index));
3810 inputs.add(mInputs.keyAt(input_index));
3811 }
3812 }
3813 // Clear any profiles associated with the disconnected device.
3814 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3815 if (mHwModules[module_index]->mHandle == 0) {
3816 continue;
3817 }
3818 for (size_t profile_index = 0;
3819 profile_index < mHwModules[module_index]->mInputProfiles.size();
3820 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003821 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003822 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003823 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003824 profile_index, module_index);
3825 if (profile->mSamplingRates[0] == 0) {
3826 profile->mSamplingRates.clear();
3827 profile->mSamplingRates.add(0);
3828 }
3829 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3830 profile->mFormats.clear();
3831 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3832 }
3833 if (profile->mChannelMasks[0] == 0) {
3834 profile->mChannelMasks.clear();
3835 profile->mChannelMasks.add(0);
3836 }
3837 }
3838 }
3839 }
3840 } // end disconnect
3841
3842 return NO_ERROR;
3843}
3844
3845
Eric Laurente0720872014-03-11 09:30:41 -07003846void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003847{
3848 ALOGV("closeOutput(%d)", output);
3849
Eric Laurent1f2f2232014-06-02 12:01:23 -07003850 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003851 if (outputDesc == NULL) {
3852 ALOGW("closeOutput() unknown output %d", output);
3853 return;
3854 }
3855
Eric Laurent275e8e92014-11-30 15:14:47 -08003856 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
3857 if (mPolicyMixes[i]->mOutput == outputDesc) {
3858 mPolicyMixes[i]->mOutput.clear();
3859 }
3860 }
3861
Eric Laurente552edb2014-03-10 17:42:56 -07003862 // look for duplicated outputs connected to the output being removed.
3863 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003864 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003865 if (dupOutputDesc->isDuplicated() &&
3866 (dupOutputDesc->mOutput1 == outputDesc ||
3867 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003868 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003869 if (dupOutputDesc->mOutput1 == outputDesc) {
3870 outputDesc2 = dupOutputDesc->mOutput2;
3871 } else {
3872 outputDesc2 = dupOutputDesc->mOutput1;
3873 }
3874 // As all active tracks on duplicated output will be deleted,
3875 // and as they were also referenced on the other output, the reference
3876 // count for their stream type must be adjusted accordingly on
3877 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003878 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003879 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003880 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003881 }
3882 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3883 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3884
3885 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003886 mOutputs.removeItem(duplicatedOutput);
3887 }
3888 }
3889
Eric Laurent05b90f82014-08-27 15:32:29 -07003890 nextAudioPortGeneration();
3891
3892 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3893 if (index >= 0) {
3894 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3895 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3896 mAudioPatches.removeItemsAt(index);
3897 mpClientInterface->onAudioPatchListUpdate();
3898 }
3899
Eric Laurente552edb2014-03-10 17:42:56 -07003900 AudioParameter param;
3901 param.add(String8("closing"), String8("true"));
3902 mpClientInterface->setParameters(output, param.toString());
3903
3904 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003905 mOutputs.removeItem(output);
3906 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003907}
3908
3909void AudioPolicyManager::closeInput(audio_io_handle_t input)
3910{
3911 ALOGV("closeInput(%d)", input);
3912
3913 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3914 if (inputDesc == NULL) {
3915 ALOGW("closeInput() unknown input %d", input);
3916 return;
3917 }
3918
Eric Laurent6a94d692014-05-20 11:18:06 -07003919 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003920
3921 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3922 if (index >= 0) {
3923 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3924 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3925 mAudioPatches.removeItemsAt(index);
3926 mpClientInterface->onAudioPatchListUpdate();
3927 }
3928
3929 mpClientInterface->closeInput(input);
3930 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003931}
3932
Eric Laurente0720872014-03-11 09:30:41 -07003933SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003934 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003935{
3936 SortedVector<audio_io_handle_t> outputs;
3937
3938 ALOGVV("getOutputsForDevice() device %04x", device);
3939 for (size_t i = 0; i < openOutputs.size(); i++) {
3940 ALOGVV("output %d isDuplicated=%d device=%04x",
3941 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3942 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3943 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3944 outputs.add(openOutputs.keyAt(i));
3945 }
3946 }
3947 return outputs;
3948}
3949
Eric Laurente0720872014-03-11 09:30:41 -07003950bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003951 SortedVector<audio_io_handle_t>& outputs2)
3952{
3953 if (outputs1.size() != outputs2.size()) {
3954 return false;
3955 }
3956 for (size_t i = 0; i < outputs1.size(); i++) {
3957 if (outputs1[i] != outputs2[i]) {
3958 return false;
3959 }
3960 }
3961 return true;
3962}
3963
Eric Laurente0720872014-03-11 09:30:41 -07003964void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003965{
3966 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3967 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3968 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3969 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3970
3971 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3972 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3973 strategy, srcOutputs[0], dstOutputs[0]);
3974 // mute strategy while moving tracks from one output to another
3975 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003976 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003977 if (desc->isStrategyActive(strategy)) {
3978 setStrategyMute(strategy, true, srcOutputs[i]);
3979 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3980 }
3981 }
3982
3983 // Move effects associated to this strategy from previous output to new output
3984 if (strategy == STRATEGY_MEDIA) {
3985 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3986 SortedVector<audio_io_handle_t> moved;
3987 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003988 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3989 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3990 effectDesc->mIo != fxOutput) {
3991 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003992 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3993 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003994 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003995 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003996 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003997 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003998 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003999 }
4000 }
4001 }
4002 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004003 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004004 if (i == AUDIO_STREAM_PATCH) {
4005 continue;
4006 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004007 if (getStrategy((audio_stream_type_t)i) == strategy) {
4008 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004009 }
4010 }
4011 }
4012}
4013
Eric Laurente0720872014-03-11 09:30:41 -07004014void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004015{
Jon Eklund966095e2014-09-09 15:39:49 -05004016 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4017 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004018 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05004019 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4020 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004021 checkOutputForStrategy(STRATEGY_SONIFICATION);
4022 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004023 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004024 checkOutputForStrategy(STRATEGY_MEDIA);
4025 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004026 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004027}
4028
Eric Laurente0720872014-03-11 09:30:41 -07004029audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07004030{
Eric Laurente552edb2014-03-10 17:42:56 -07004031 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004032 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004033 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
4034 return mOutputs.keyAt(i);
4035 }
4036 }
4037
4038 return 0;
4039}
4040
Eric Laurente0720872014-03-11 09:30:41 -07004041void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004042{
Eric Laurente552edb2014-03-10 17:42:56 -07004043 audio_io_handle_t a2dpOutput = getA2dpOutput();
4044 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004045 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004046 return;
4047 }
4048
Eric Laurent3a4311c2014-03-17 12:00:47 -07004049 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004050 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4051 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4052 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004053 // suspend A2DP output if:
4054 // (NOT already suspended) &&
4055 // ((SCO device is connected &&
4056 // (forced usage for communication || for record is SCO))) ||
4057 // (phone state is ringing || in call)
4058 //
4059 // restore A2DP output if:
4060 // (Already suspended) &&
4061 // ((SCO device is NOT connected ||
4062 // (forced usage NOT for communication && NOT for record is SCO))) &&
4063 // (phone state is NOT ringing && NOT in call)
4064 //
4065 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004066 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004067 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
4068 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
4069 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
4070 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004071
4072 mpClientInterface->restoreOutput(a2dpOutput);
4073 mA2dpSuspended = false;
4074 }
4075 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004076 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004077 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4078 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
4079 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
4080 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004081
4082 mpClientInterface->suspendOutput(a2dpOutput);
4083 mA2dpSuspended = true;
4084 }
4085 }
4086}
4087
Eric Laurent1c333e22014-05-20 10:48:17 -07004088audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004089{
4090 audio_devices_t device = AUDIO_DEVICE_NONE;
4091
Eric Laurent1f2f2232014-06-02 12:01:23 -07004092 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004093
4094 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4095 if (index >= 0) {
4096 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4097 if (patchDesc->mUid != mUidCached) {
4098 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4099 outputDesc->device(), outputDesc->mPatchHandle);
4100 return outputDesc->device();
4101 }
4102 }
4103
Eric Laurente552edb2014-03-10 17:42:56 -07004104 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004105 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004106 // use device for strategy enforced audible
4107 // 2: we are in call or the strategy phone is active on the output:
4108 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004109 // 3: the strategy for enforced audible is active but not enforced on the output:
4110 // use the device for strategy enforced audible
4111 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004112 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05004113 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004114 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004115 // 6: the strategy accessibility is active on the output:
4116 // use device for strategy accessibility
4117 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004118 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004119 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004120 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004121 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004122 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05004123 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
4124 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004125 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4126 } else if (isInCall() ||
4127 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
4128 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05004129 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
4130 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004131 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
4132 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
4133 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
4134 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004135 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
4136 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004137 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
4138 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
4139 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
4140 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004141 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
4142 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004143 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
4144 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004145 }
4146
Eric Laurent1c333e22014-05-20 10:48:17 -07004147 ALOGV("getNewOutputDevice() selected device %x", device);
4148 return device;
4149}
4150
4151audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4152{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004153 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004154
4155 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4156 if (index >= 0) {
4157 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4158 if (patchDesc->mUid != mUidCached) {
4159 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4160 inputDesc->mDevice, inputDesc->mPatchHandle);
4161 return inputDesc->mDevice;
4162 }
4163 }
4164
Eric Laurent1c333e22014-05-20 10:48:17 -07004165 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
4166
4167 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004168 return device;
4169}
4170
Eric Laurente0720872014-03-11 09:30:41 -07004171uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004172 return (uint32_t)getStrategy(stream);
4173}
4174
Eric Laurente0720872014-03-11 09:30:41 -07004175audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004176 // By checking the range of stream before calling getStrategy, we avoid
4177 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4178 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004179 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004180 return AUDIO_DEVICE_NONE;
4181 }
4182 audio_devices_t devices;
4183 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
4184 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4185 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4186 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004187 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07004188 if (outputDesc->isStrategyActive(strategy)) {
4189 devices = outputDesc->device();
4190 break;
4191 }
Eric Laurente552edb2014-03-10 17:42:56 -07004192 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004193
4194 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4195 and doesn't really need to.*/
4196 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4197 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4198 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4199 }
4200
Eric Laurente552edb2014-03-10 17:42:56 -07004201 return devices;
4202}
4203
Eric Laurente0720872014-03-11 09:30:41 -07004204AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004205 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004206
4207 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4208
Eric Laurente552edb2014-03-10 17:42:56 -07004209 // stream to strategy mapping
4210 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004211 case AUDIO_STREAM_VOICE_CALL:
4212 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004213 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004214 case AUDIO_STREAM_RING:
4215 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004216 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004217 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004218 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004219 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004220 return STRATEGY_DTMF;
4221 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004222 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004223 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004224 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4225 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004226 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004227 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004228 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004229 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004230 case AUDIO_STREAM_TTS:
4231 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004232 case AUDIO_STREAM_ACCESSIBILITY:
4233 return STRATEGY_ACCESSIBILITY;
4234 case AUDIO_STREAM_REROUTING:
4235 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004236 }
4237}
4238
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004239uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4240 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004241 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4242 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4243 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004244 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4245 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4246 }
4247
4248 // usage to strategy mapping
4249 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004250 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4251 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4252 return (uint32_t) STRATEGY_SONIFICATION;
4253 }
4254 if (isInCall()) {
4255 return (uint32_t) STRATEGY_PHONE;
4256 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004257 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004258
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004259 case AUDIO_USAGE_MEDIA:
4260 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004261 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4262 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4263 return (uint32_t) STRATEGY_MEDIA;
4264
4265 case AUDIO_USAGE_VOICE_COMMUNICATION:
4266 return (uint32_t) STRATEGY_PHONE;
4267
4268 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4269 return (uint32_t) STRATEGY_DTMF;
4270
4271 case AUDIO_USAGE_ALARM:
4272 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4273 return (uint32_t) STRATEGY_SONIFICATION;
4274
4275 case AUDIO_USAGE_NOTIFICATION:
4276 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4277 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4278 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4279 case AUDIO_USAGE_NOTIFICATION_EVENT:
4280 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4281
4282 case AUDIO_USAGE_UNKNOWN:
4283 default:
4284 return (uint32_t) STRATEGY_MEDIA;
4285 }
4286}
4287
Eric Laurente0720872014-03-11 09:30:41 -07004288void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004289 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004290 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004291 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4292 updateDevicesAndOutputs();
4293 break;
4294 default:
4295 break;
4296 }
4297}
4298
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004299bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4300 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4301 if (s == (size_t) streamToIgnore) {
4302 continue;
4303 }
4304 for (size_t i = 0; i < mOutputs.size(); i++) {
4305 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4306 if (outputDesc->mRefCount[s] != 0) {
4307 return true;
4308 }
4309 }
4310 }
4311 return false;
4312}
4313
4314uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4315 switch(event) {
4316 case STARTING_OUTPUT:
4317 mBeaconMuteRefCount++;
4318 break;
4319 case STOPPING_OUTPUT:
4320 if (mBeaconMuteRefCount > 0) {
4321 mBeaconMuteRefCount--;
4322 }
4323 break;
4324 case STARTING_BEACON:
4325 mBeaconPlayingRefCount++;
4326 break;
4327 case STOPPING_BEACON:
4328 if (mBeaconPlayingRefCount > 0) {
4329 mBeaconPlayingRefCount--;
4330 }
4331 break;
4332 }
4333
4334 if (mBeaconMuteRefCount > 0) {
4335 // any playback causes beacon to be muted
4336 return setBeaconMute(true);
4337 } else {
4338 // no other playback: unmute when beacon starts playing, mute when it stops
4339 return setBeaconMute(mBeaconPlayingRefCount == 0);
4340 }
4341}
4342
4343uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4344 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4345 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4346 // keep track of muted state to avoid repeating mute/unmute operations
4347 if (mBeaconMuted != mute) {
4348 // mute/unmute AUDIO_STREAM_TTS on all outputs
4349 ALOGV("\t muting %d", mute);
4350 uint32_t maxLatency = 0;
4351 for (size_t i = 0; i < mOutputs.size(); i++) {
4352 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4353 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4354 desc->mIoHandle,
4355 0 /*delay*/, AUDIO_DEVICE_NONE);
4356 const uint32_t latency = desc->latency() * 2;
4357 if (latency > maxLatency) {
4358 maxLatency = latency;
4359 }
4360 }
4361 mBeaconMuted = mute;
4362 return maxLatency;
4363 }
4364 return 0;
4365}
4366
Eric Laurente0720872014-03-11 09:30:41 -07004367audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004368 bool fromCache)
4369{
4370 uint32_t device = AUDIO_DEVICE_NONE;
4371
4372 if (fromCache) {
4373 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4374 strategy, mDeviceForStrategy[strategy]);
4375 return mDeviceForStrategy[strategy];
4376 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004377 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004378 switch (strategy) {
4379
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004380 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4381 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4382 if (!device) {
4383 ALOGE("getDeviceForStrategy() no device found for "\
4384 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4385 }
4386 break;
4387
Eric Laurente552edb2014-03-10 17:42:56 -07004388 case STRATEGY_SONIFICATION_RESPECTFUL:
4389 if (isInCall()) {
4390 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004391 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004392 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4393 // while media is playing on a remote device, use the the sonification behavior.
4394 // Note that we test this usecase before testing if media is playing because
4395 // the isStreamActive() method only informs about the activity of a stream, not
4396 // if it's for local playback. Note also that we use the same delay between both tests
4397 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004398 //user "safe" speaker if available instead of normal speaker to avoid triggering
4399 //other acoustic safety mechanisms for notification
4400 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4401 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004402 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004403 // while media is playing (or has recently played), use the same device
4404 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4405 } else {
4406 // when media is not playing anymore, fall back on the sonification behavior
4407 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004408 //user "safe" speaker if available instead of normal speaker to avoid triggering
4409 //other acoustic safety mechanisms for notification
4410 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4411 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004412 }
4413
4414 break;
4415
4416 case STRATEGY_DTMF:
4417 if (!isInCall()) {
4418 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4419 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4420 break;
4421 }
4422 // when in call, DTMF and PHONE strategies follow the same rules
4423 // FALL THROUGH
4424
4425 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004426 // Force use of only devices on primary output if:
4427 // - in call AND
4428 // - cannot route from voice call RX OR
4429 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4430 if (mPhoneState == AUDIO_MODE_IN_CALL) {
4431 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4432 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4433 if (((mAvailableInputDevices.types() &
4434 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4435 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004436 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004437 AUDIO_DEVICE_API_VERSION_3_0))) {
4438 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4439 }
4440 }
Eric Laurente552edb2014-03-10 17:42:56 -07004441 // for phone strategy, we first consider the forced use and then the available devices by order
4442 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004443 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4444 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004445 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004446 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004447 if (device) break;
4448 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004449 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004450 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004451 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004452 if (device) break;
4453 // if SCO device is requested but no SCO device is available, fall back to default case
4454 // FALL THROUGH
4455
4456 default: // FORCE_NONE
4457 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004458 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004459 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004460 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004461 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004462 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004463 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004464 if (device) break;
4465 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004466 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004467 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004468 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004469 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004470 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4471 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004472 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004473 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004474 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004475 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004476 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004477 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004478 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004479 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004480 if (device) break;
4481 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004482 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004483 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004484 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004485 if (device == AUDIO_DEVICE_NONE) {
4486 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4487 }
4488 break;
4489
Eric Laurent3b73df72014-03-11 09:06:29 -07004490 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004491 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4492 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004493 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004494 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004495 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004496 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004497 if (device) break;
4498 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004499 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004500 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004501 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004502 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004503 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004504 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004505 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004506 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004507 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004508 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004509 if (device) break;
4510 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004511 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4512 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004513 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004514 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004515 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004516 if (device == AUDIO_DEVICE_NONE) {
4517 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4518 }
4519 break;
4520 }
4521 break;
4522
4523 case STRATEGY_SONIFICATION:
4524
4525 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4526 // handleIncallSonification().
4527 if (isInCall()) {
4528 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4529 break;
4530 }
4531 // FALL THROUGH
4532
4533 case STRATEGY_ENFORCED_AUDIBLE:
4534 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4535 // except:
4536 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4537 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4538
4539 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004540 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004541 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004542 if (device == AUDIO_DEVICE_NONE) {
4543 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4544 }
4545 }
4546 // The second device used for sonification is the same as the device used by media strategy
4547 // FALL THROUGH
4548
Eric Laurent223fd5c2014-11-11 13:43:36 -08004549 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4550 case STRATEGY_ACCESSIBILITY:
Eric Laurent066ceec2014-11-25 12:35:01 -08004551 if (strategy == STRATEGY_ACCESSIBILITY) {
4552 // do not route accessibility prompts to a digital output currently configured with a
4553 // compressed format as they would likely not be mixed and dropped.
4554 for (size_t i = 0; i < mOutputs.size(); i++) {
4555 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4556 audio_devices_t devices = desc->device() &
4557 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4558 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4559 devices != AUDIO_DEVICE_NONE) {
4560 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4561 }
4562 }
4563 }
4564 // FALL THROUGH
4565
Eric Laurent223fd5c2014-11-11 13:43:36 -08004566 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004567 case STRATEGY_MEDIA: {
4568 uint32_t device2 = AUDIO_DEVICE_NONE;
4569 if (strategy != STRATEGY_SONIFICATION) {
4570 // no sonification on remote submix (e.g. WFD)
Eric Laurent275e8e92014-11-30 15:14:47 -08004571 if (mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, String8("0")) != 0) {
4572 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
4573 }
Eric Laurente552edb2014-03-10 17:42:56 -07004574 }
4575 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004576 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004577 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004578 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004579 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004580 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004581 }
4582 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004583 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004584 }
4585 }
Hochi Huang327cb702014-09-21 09:47:31 +08004586 if ((device2 == AUDIO_DEVICE_NONE) &&
4587 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4588 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4589 }
Eric Laurente552edb2014-03-10 17:42:56 -07004590 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004591 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004592 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004593 if ((device2 == AUDIO_DEVICE_NONE)) {
4594 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4595 }
Eric Laurente552edb2014-03-10 17:42:56 -07004596 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004597 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004598 }
4599 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004600 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004601 }
4602 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004603 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004604 }
4605 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004606 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004607 }
4608 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4609 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004610 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004611 }
4612 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004613 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004614 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004615 }
4616 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004617 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004618 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004619 int device3 = AUDIO_DEVICE_NONE;
4620 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004621 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004622 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4623 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004624 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004625 }
Eric Laurente552edb2014-03-10 17:42:56 -07004626
Jungshik Jang839e4f32014-06-26 17:23:40 +09004627 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004628 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4629 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4630 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004631
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004632 // If hdmi system audio mode is on, remove speaker out of output list.
4633 if ((strategy == STRATEGY_MEDIA) &&
4634 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4635 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4636 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4637 }
4638
Eric Laurente552edb2014-03-10 17:42:56 -07004639 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004640 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004641 if (device == AUDIO_DEVICE_NONE) {
4642 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4643 }
4644 } break;
4645
4646 default:
4647 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4648 break;
4649 }
4650
4651 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4652 return device;
4653}
4654
Eric Laurente0720872014-03-11 09:30:41 -07004655void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004656{
4657 for (int i = 0; i < NUM_STRATEGIES; i++) {
4658 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4659 }
4660 mPreviousOutputs = mOutputs;
4661}
4662
Eric Laurent1f2f2232014-06-02 12:01:23 -07004663uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004664 audio_devices_t prevDevice,
4665 uint32_t delayMs)
4666{
4667 // mute/unmute strategies using an incompatible device combination
4668 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4669 // if unmuting, unmute only after the specified delay
4670 if (outputDesc->isDuplicated()) {
4671 return 0;
4672 }
4673
4674 uint32_t muteWaitMs = 0;
4675 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004676 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004677
4678 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4679 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004680 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004681 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4682 bool doMute = false;
4683
4684 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4685 doMute = true;
4686 outputDesc->mStrategyMutedByDevice[i] = true;
4687 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4688 doMute = true;
4689 outputDesc->mStrategyMutedByDevice[i] = false;
4690 }
Eric Laurent99401132014-05-07 19:48:15 -07004691 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004692 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004693 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004694 // skip output if it does not share any device with current output
4695 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4696 == AUDIO_DEVICE_NONE) {
4697 continue;
4698 }
4699 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4700 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4701 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4702 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4703 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004704 if (mute) {
4705 // FIXME: should not need to double latency if volume could be applied
4706 // immediately by the audioflinger mixer. We must account for the delay
4707 // between now and the next time the audioflinger thread for this output
4708 // will process a buffer (which corresponds to one buffer size,
4709 // usually 1/2 or 1/4 of the latency).
4710 if (muteWaitMs < desc->latency() * 2) {
4711 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004712 }
4713 }
4714 }
4715 }
4716 }
4717 }
4718
Eric Laurent99401132014-05-07 19:48:15 -07004719 // temporary mute output if device selection changes to avoid volume bursts due to
4720 // different per device volumes
4721 if (outputDesc->isActive() && (device != prevDevice)) {
4722 if (muteWaitMs < outputDesc->latency() * 2) {
4723 muteWaitMs = outputDesc->latency() * 2;
4724 }
4725 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4726 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004727 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004728 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004729 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004730 muteWaitMs *2, device);
4731 }
4732 }
4733 }
4734
Eric Laurente552edb2014-03-10 17:42:56 -07004735 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4736 if (muteWaitMs > delayMs) {
4737 muteWaitMs -= delayMs;
4738 usleep(muteWaitMs * 1000);
4739 return muteWaitMs;
4740 }
4741 return 0;
4742}
4743
Eric Laurente0720872014-03-11 09:30:41 -07004744uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004745 audio_devices_t device,
4746 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004747 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004748 audio_patch_handle_t *patchHandle,
4749 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004750{
4751 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004752 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004753 AudioParameter param;
4754 uint32_t muteWaitMs;
4755
4756 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004757 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4758 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004759 return muteWaitMs;
4760 }
4761 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4762 // output profile
4763 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004764 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004765 return 0;
4766 }
4767
4768 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004769 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004770
4771 audio_devices_t prevDevice = outputDesc->mDevice;
4772
4773 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4774
4775 if (device != AUDIO_DEVICE_NONE) {
4776 outputDesc->mDevice = device;
4777 }
4778 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4779
4780 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004781 // the requested device is AUDIO_DEVICE_NONE
4782 // OR the requested device is the same as current device
4783 // AND force is not specified
4784 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004785 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004786 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4787 outputDesc->mPatchHandle != 0) {
4788 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4789 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004790 return muteWaitMs;
4791 }
4792
4793 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004794
Eric Laurente552edb2014-03-10 17:42:56 -07004795 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004796 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004797 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004798 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004799 DeviceVector deviceList = (address == NULL) ?
4800 mAvailableOutputDevices.getDevicesFromType(device)
4801 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004802 if (!deviceList.isEmpty()) {
4803 struct audio_patch patch;
4804 outputDesc->toAudioPortConfig(&patch.sources[0]);
4805 patch.num_sources = 1;
4806 patch.num_sinks = 0;
4807 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4808 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004809 patch.num_sinks++;
4810 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004811 ssize_t index;
4812 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4813 index = mAudioPatches.indexOfKey(*patchHandle);
4814 } else {
4815 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4816 }
4817 sp< AudioPatch> patchDesc;
4818 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4819 if (index >= 0) {
4820 patchDesc = mAudioPatches.valueAt(index);
4821 afPatchHandle = patchDesc->mAfPatchHandle;
4822 }
4823
Eric Laurent1c333e22014-05-20 10:48:17 -07004824 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004825 &afPatchHandle,
4826 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004827 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4828 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004829 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004830 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004831 if (index < 0) {
4832 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4833 &patch, mUidCached);
4834 addAudioPatch(patchDesc->mHandle, patchDesc);
4835 } else {
4836 patchDesc->mPatch = patch;
4837 }
4838 patchDesc->mAfPatchHandle = afPatchHandle;
4839 patchDesc->mUid = mUidCached;
4840 if (patchHandle) {
4841 *patchHandle = patchDesc->mHandle;
4842 }
4843 outputDesc->mPatchHandle = patchDesc->mHandle;
4844 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004845 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004846 }
4847 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004848
4849 // inform all input as well
4850 for (size_t i = 0; i < mInputs.size(); i++) {
4851 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4852 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4853 AudioParameter inputCmd = AudioParameter();
4854 ALOGV("%s: inform input %d of device:%d", __func__,
4855 inputDescriptor->mIoHandle, device);
4856 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4857 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4858 inputCmd.toString(),
4859 delayMs);
4860 }
4861 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004862 }
Eric Laurente552edb2014-03-10 17:42:56 -07004863
4864 // update stream volumes according to new device
4865 applyStreamVolumes(output, device, delayMs);
4866
4867 return muteWaitMs;
4868}
4869
Eric Laurent1c333e22014-05-20 10:48:17 -07004870status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004871 int delayMs,
4872 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004873{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004874 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004875 ssize_t index;
4876 if (patchHandle) {
4877 index = mAudioPatches.indexOfKey(*patchHandle);
4878 } else {
4879 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4880 }
4881 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004882 return INVALID_OPERATION;
4883 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004884 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4885 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004886 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4887 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004888 removeAudioPatch(patchDesc->mHandle);
4889 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004890 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004891 return status;
4892}
4893
4894status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4895 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004896 bool force,
4897 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004898{
4899 status_t status = NO_ERROR;
4900
Eric Laurent1f2f2232014-06-02 12:01:23 -07004901 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004902 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4903 inputDesc->mDevice = device;
4904
4905 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4906 if (!deviceList.isEmpty()) {
4907 struct audio_patch patch;
4908 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004909 // AUDIO_SOURCE_HOTWORD is for internal use only:
4910 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004911 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4912 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004913 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4914 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004915 patch.num_sinks = 1;
4916 //only one input device for now
4917 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004918 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004919 ssize_t index;
4920 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4921 index = mAudioPatches.indexOfKey(*patchHandle);
4922 } else {
4923 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4924 }
4925 sp< AudioPatch> patchDesc;
4926 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4927 if (index >= 0) {
4928 patchDesc = mAudioPatches.valueAt(index);
4929 afPatchHandle = patchDesc->mAfPatchHandle;
4930 }
4931
Eric Laurent1c333e22014-05-20 10:48:17 -07004932 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004933 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004934 0);
4935 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004936 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004937 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004938 if (index < 0) {
4939 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4940 &patch, mUidCached);
4941 addAudioPatch(patchDesc->mHandle, patchDesc);
4942 } else {
4943 patchDesc->mPatch = patch;
4944 }
4945 patchDesc->mAfPatchHandle = afPatchHandle;
4946 patchDesc->mUid = mUidCached;
4947 if (patchHandle) {
4948 *patchHandle = patchDesc->mHandle;
4949 }
4950 inputDesc->mPatchHandle = patchDesc->mHandle;
4951 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004952 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004953 }
4954 }
4955 }
4956 return status;
4957}
4958
Eric Laurent6a94d692014-05-20 11:18:06 -07004959status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4960 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004961{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004962 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004963 ssize_t index;
4964 if (patchHandle) {
4965 index = mAudioPatches.indexOfKey(*patchHandle);
4966 } else {
4967 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4968 }
4969 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004970 return INVALID_OPERATION;
4971 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004972 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4973 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004974 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4975 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004976 removeAudioPatch(patchDesc->mHandle);
4977 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004978 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004979 return status;
4980}
4981
4982sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08004983 String8 address,
Glenn Kastencbd48022014-07-24 13:46:44 -07004984 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004985 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004986 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004987 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004988{
4989 // Choose an input profile based on the requested capture parameters: select the first available
4990 // profile supporting all requested parameters.
4991
4992 for (size_t i = 0; i < mHwModules.size(); i++)
4993 {
4994 if (mHwModules[i]->mHandle == 0) {
4995 continue;
4996 }
4997 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4998 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004999 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005000 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005001 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005002 &samplingRate /*updatedSamplingRate*/,
5003 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005004
Eric Laurente552edb2014-03-10 17:42:56 -07005005 return profile;
5006 }
5007 }
5008 }
5009 return NULL;
5010}
5011
Eric Laurent275e8e92014-11-30 15:14:47 -08005012audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource,
5013 String8 *address)
Eric Laurente552edb2014-03-10 17:42:56 -07005014{
5015 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005016 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5017 ~AUDIO_DEVICE_BIT_IN;
Eric Laurent275e8e92014-11-30 15:14:47 -08005018
5019 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
5020 if (mPolicyMixes[i]->mMix.mMixType != MIX_TYPE_RECORDERS) {
5021 continue;
5022 }
5023 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
5024 if ((RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5025 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource == inputSource) ||
5026 (RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5027 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource != inputSource)) {
5028 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
5029 if (address != NULL) {
5030 *address = mPolicyMixes[i]->mMix.mRegistrationId;
5031 }
5032 return AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5033 }
5034 break;
5035 }
5036 }
5037 }
5038
Eric Laurente552edb2014-03-10 17:42:56 -07005039 switch (inputSource) {
5040 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005041 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005042 device = AUDIO_DEVICE_IN_VOICE_CALL;
5043 break;
5044 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005045 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005046
5047 case AUDIO_SOURCE_DEFAULT:
5048 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07005049 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
5050 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07005051 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5052 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5053 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5054 device = AUDIO_DEVICE_IN_USB_DEVICE;
5055 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5056 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005057 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005058 break;
5059
5060 case AUDIO_SOURCE_VOICE_COMMUNICATION:
5061 // Allow only use of devices on primary input if in call and HAL does not support routing
5062 // to voice call path.
5063 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
5064 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
5065 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
5066 }
5067
5068 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
5069 case AUDIO_POLICY_FORCE_BT_SCO:
5070 // if SCO device is requested but no SCO device is available, fall back to default case
5071 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
5072 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
5073 break;
5074 }
5075 // FALL THROUGH
5076
5077 default: // FORCE_NONE
5078 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5079 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5080 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5081 device = AUDIO_DEVICE_IN_USB_DEVICE;
5082 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5083 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5084 }
5085 break;
5086
5087 case AUDIO_POLICY_FORCE_SPEAKER:
5088 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
5089 device = AUDIO_DEVICE_IN_BACK_MIC;
5090 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5091 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5092 }
5093 break;
5094 }
5095 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005096
Eric Laurente552edb2014-03-10 17:42:56 -07005097 case AUDIO_SOURCE_VOICE_RECOGNITION:
5098 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07005099 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005100 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005101 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005102 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005103 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07005104 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5105 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005106 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005107 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5108 }
5109 break;
5110 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005111 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005112 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005113 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005114 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5115 }
5116 break;
5117 case AUDIO_SOURCE_VOICE_DOWNLINK:
5118 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005119 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005120 device = AUDIO_DEVICE_IN_VOICE_CALL;
5121 }
5122 break;
5123 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005124 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07005125 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
Eric Laurent275e8e92014-11-30 15:14:47 -08005126 if (address != NULL) {
5127 *address = "0";
5128 }
Eric Laurente552edb2014-03-10 17:42:56 -07005129 }
5130 break;
Hochi Huang327cb702014-09-21 09:47:31 +08005131 case AUDIO_SOURCE_FM_TUNER:
5132 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
5133 device = AUDIO_DEVICE_IN_FM_TUNER;
5134 }
5135 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005136 default:
5137 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
5138 break;
5139 }
5140 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
5141 return device;
5142}
5143
Eric Laurente0720872014-03-11 09:30:41 -07005144bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005145{
5146 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
5147 device &= ~AUDIO_DEVICE_BIT_IN;
5148 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
5149 return true;
5150 }
5151 return false;
5152}
5153
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005154bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005155 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL & ~AUDIO_DEVICE_BIT_IN) != 0);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005156}
5157
Eric Laurente0720872014-03-11 09:30:41 -07005158audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005159{
5160 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005161 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07005162 if ((input_descriptor->mRefCount > 0)
5163 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
5164 return mInputs.keyAt(i);
5165 }
5166 }
5167 return 0;
5168}
5169
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005170uint32_t AudioPolicyManager::activeInputsCount() const
5171{
5172 uint32_t count = 0;
5173 for (size_t i = 0; i < mInputs.size(); i++) {
5174 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
5175 if (desc->mRefCount > 0) {
5176 return count++;
5177 }
5178 }
5179 return count;
5180}
5181
Eric Laurente552edb2014-03-10 17:42:56 -07005182
Eric Laurente0720872014-03-11 09:30:41 -07005183audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005184{
5185 if (device == AUDIO_DEVICE_NONE) {
5186 // this happens when forcing a route update and no track is active on an output.
5187 // In this case the returned category is not important.
5188 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07005189 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07005190 // Multiple device selection is either:
5191 // - speaker + one other device: give priority to speaker in this case.
5192 // - one A2DP device + another device: happens with duplicated output. In this case
5193 // retain the device on the A2DP output as the other must not correspond to an active
5194 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09005195 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07005196 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
5197 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09005198 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
5199 device = AUDIO_DEVICE_OUT_HDMI_ARC;
5200 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
5201 device = AUDIO_DEVICE_OUT_AUX_LINE;
5202 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
5203 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07005204 } else {
5205 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
5206 }
5207 }
5208
Jon Eklund11c9fb12014-06-23 14:47:03 -05005209 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
5210 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
5211 device = AUDIO_DEVICE_OUT_SPEAKER;
5212
Eric Laurent3b73df72014-03-11 09:06:29 -07005213 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07005214 "getDeviceForVolume() invalid device combination: %08x",
5215 device);
5216
5217 return device;
5218}
5219
Eric Laurente0720872014-03-11 09:30:41 -07005220AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005221{
5222 switch(getDeviceForVolume(device)) {
5223 case AUDIO_DEVICE_OUT_EARPIECE:
5224 return DEVICE_CATEGORY_EARPIECE;
5225 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5226 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5227 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5228 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5229 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5230 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5231 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05005232 case AUDIO_DEVICE_OUT_LINE:
5233 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5234 /*USB? Remote submix?*/
5235 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07005236 case AUDIO_DEVICE_OUT_SPEAKER:
5237 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5238 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005239 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5240 case AUDIO_DEVICE_OUT_USB_DEVICE:
5241 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5242 default:
5243 return DEVICE_CATEGORY_SPEAKER;
5244 }
5245}
5246
Eric Laurent223fd5c2014-11-11 13:43:36 -08005247/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005248float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005249 int indexInUi)
5250{
5251 device_category deviceCategory = getDeviceCategory(device);
5252 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5253
5254 // the volume index in the UI is relative to the min and max volume indices for this stream type
5255 int nbSteps = 1 + curve[VOLMAX].mIndex -
5256 curve[VOLMIN].mIndex;
5257 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5258 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5259
5260 // find what part of the curve this index volume belongs to, or if it's out of bounds
5261 int segment = 0;
5262 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5263 return 0.0f;
5264 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5265 segment = 0;
5266 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5267 segment = 1;
5268 } else if (volIdx <= curve[VOLMAX].mIndex) {
5269 segment = 2;
5270 } else { // out of bounds
5271 return 1.0f;
5272 }
5273
5274 // linear interpolation in the attenuation table in dB
5275 float decibels = curve[segment].mDBAttenuation +
5276 ((float)(volIdx - curve[segment].mIndex)) *
5277 ( (curve[segment+1].mDBAttenuation -
5278 curve[segment].mDBAttenuation) /
5279 ((float)(curve[segment+1].mIndex -
5280 curve[segment].mIndex)) );
5281
5282 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5283
5284 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5285 curve[segment].mIndex, volIdx,
5286 curve[segment+1].mIndex,
5287 curve[segment].mDBAttenuation,
5288 decibels,
5289 curve[segment+1].mDBAttenuation,
5290 amplification);
5291
5292 return amplification;
5293}
5294
Eric Laurente0720872014-03-11 09:30:41 -07005295const AudioPolicyManager::VolumeCurvePoint
5296 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005297 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5298};
5299
Eric Laurente0720872014-03-11 09:30:41 -07005300const AudioPolicyManager::VolumeCurvePoint
5301 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005302 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5303};
5304
Eric Laurente0720872014-03-11 09:30:41 -07005305const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005306 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5307 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5308};
5309
5310const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005311 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005312 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5313};
5314
Eric Laurente0720872014-03-11 09:30:41 -07005315const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005316 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005317 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005318};
5319
5320const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005321 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005322 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5323};
5324
Eric Laurente0720872014-03-11 09:30:41 -07005325const AudioPolicyManager::VolumeCurvePoint
5326 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005327 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5328};
5329
5330// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5331// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5332// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5333// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5334
Eric Laurente0720872014-03-11 09:30:41 -07005335const AudioPolicyManager::VolumeCurvePoint
5336 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005337 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5338};
5339
Eric Laurente0720872014-03-11 09:30:41 -07005340const AudioPolicyManager::VolumeCurvePoint
5341 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005342 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5343};
5344
Eric Laurente0720872014-03-11 09:30:41 -07005345const AudioPolicyManager::VolumeCurvePoint
5346 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005347 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5348};
5349
Eric Laurente0720872014-03-11 09:30:41 -07005350const AudioPolicyManager::VolumeCurvePoint
5351 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005352 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5353};
5354
Eric Laurente0720872014-03-11 09:30:41 -07005355const AudioPolicyManager::VolumeCurvePoint
5356 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005357 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5358};
5359
Eric Laurente0720872014-03-11 09:30:41 -07005360const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005361 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5362 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5363};
5364
5365const AudioPolicyManager::VolumeCurvePoint
5366 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5367 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5368};
5369
5370const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005371 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5372 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5373};
5374
5375const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005376 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5377 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005378 { // AUDIO_STREAM_VOICE_CALL
5379 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5380 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005381 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5382 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005383 },
5384 { // AUDIO_STREAM_SYSTEM
5385 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5386 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005387 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5388 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005389 },
5390 { // AUDIO_STREAM_RING
5391 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5392 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005393 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5394 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005395 },
5396 { // AUDIO_STREAM_MUSIC
5397 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5398 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005399 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5400 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005401 },
5402 { // AUDIO_STREAM_ALARM
5403 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5404 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005405 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5406 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005407 },
5408 { // AUDIO_STREAM_NOTIFICATION
5409 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5410 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005411 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5412 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005413 },
5414 { // AUDIO_STREAM_BLUETOOTH_SCO
5415 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5416 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005417 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5418 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005419 },
5420 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5421 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5422 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005423 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5424 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005425 },
5426 { // AUDIO_STREAM_DTMF
5427 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5428 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005429 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5430 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005431 },
5432 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005433 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5434 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5435 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5436 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5437 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005438 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005439 { // AUDIO_STREAM_ACCESSIBILITY
5440 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5441 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5442 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5443 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5444 },
5445 { // AUDIO_STREAM_REROUTING
5446 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5447 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5448 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5449 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5450 },
5451 { // AUDIO_STREAM_PATCH
5452 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5453 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5454 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5455 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5456 },
Eric Laurente552edb2014-03-10 17:42:56 -07005457};
5458
Eric Laurente0720872014-03-11 09:30:41 -07005459void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005460{
5461 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5462 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5463 mStreams[i].mVolumeCurve[j] =
5464 sVolumeProfiles[i][j];
5465 }
5466 }
5467
5468 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5469 if (mSpeakerDrcEnabled) {
5470 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5471 sDefaultSystemVolumeCurveDrc;
5472 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5473 sSpeakerSonificationVolumeCurveDrc;
5474 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5475 sSpeakerSonificationVolumeCurveDrc;
5476 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5477 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005478 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5479 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005480 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5481 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005482 }
5483}
5484
Eric Laurente0720872014-03-11 09:30:41 -07005485float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005486 int index,
5487 audio_io_handle_t output,
5488 audio_devices_t device)
5489{
5490 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005491 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005492 StreamDescriptor &streamDesc = mStreams[stream];
5493
5494 if (device == AUDIO_DEVICE_NONE) {
5495 device = outputDesc->device();
5496 }
5497
Eric Laurente552edb2014-03-10 17:42:56 -07005498 volume = volIndexToAmpl(device, streamDesc, index);
5499
5500 // if a headset is connected, apply the following rules to ring tones and notifications
5501 // to avoid sound level bursts in user's ears:
5502 // - always attenuate ring tones and notifications volume by 6dB
5503 // - if music is playing, always limit the volume to current music volume,
5504 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005505 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005506 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5507 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5508 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5509 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5510 ((stream_strategy == STRATEGY_SONIFICATION)
5511 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005512 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005513 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005514 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005515 streamDesc.mCanBeMuted) {
5516 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5517 // when the phone is ringing we must consider that music could have been paused just before
5518 // by the music application and behave as if music was active if the last music track was
5519 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005520 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005521 mLimitRingtoneVolume) {
5522 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005523 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5524 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005525 output,
5526 musicDevice);
5527 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5528 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5529 if (volume > minVol) {
5530 volume = minVol;
5531 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5532 }
5533 }
5534 }
5535
5536 return volume;
5537}
5538
Eric Laurente0720872014-03-11 09:30:41 -07005539status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005540 int index,
5541 audio_io_handle_t output,
5542 audio_devices_t device,
5543 int delayMs,
5544 bool force)
5545{
5546
5547 // do not change actual stream volume if the stream is muted
5548 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5549 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5550 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5551 return NO_ERROR;
5552 }
5553
5554 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005555 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5556 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5557 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5558 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005559 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005560 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005561 return INVALID_OPERATION;
5562 }
5563
5564 float volume = computeVolume(stream, index, output, device);
Eric Laurent275e8e92014-11-30 15:14:47 -08005565 // unit gain if rerouting to external policy
5566 if (device == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
5567 ssize_t index = mOutputs.indexOfKey(output);
5568 if (index >= 0) {
5569 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
5570 if (outputDesc->mPolicyMixAddress != String8("")
5571 && outputDesc->mPolicyMixAddress != String8("0")) {
5572 ALOGV("max gain when rerouting for output=%d", output);
5573 volume = 1.0f;
5574 }
5575 }
5576
5577 }
Eric Laurente552edb2014-03-10 17:42:56 -07005578 // We actually change the volume if:
5579 // - the float value returned by computeVolume() changed
5580 // - the force flag is set
5581 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5582 force) {
5583 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5584 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5585 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5586 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005587 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5588 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005589 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005590 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005591 }
5592
Eric Laurent3b73df72014-03-11 09:06:29 -07005593 if (stream == AUDIO_STREAM_VOICE_CALL ||
5594 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005595 float voiceVolume;
5596 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005597 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005598 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5599 } else {
5600 voiceVolume = 1.0;
5601 }
5602
5603 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5604 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5605 mLastVoiceVolume = voiceVolume;
5606 }
5607 }
5608
5609 return NO_ERROR;
5610}
5611
Eric Laurente0720872014-03-11 09:30:41 -07005612void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005613 audio_devices_t device,
5614 int delayMs,
5615 bool force)
5616{
5617 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5618
Eric Laurent3b73df72014-03-11 09:06:29 -07005619 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005620 if (stream == AUDIO_STREAM_PATCH) {
5621 continue;
5622 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005623 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005624 mStreams[stream].getVolumeIndex(device),
5625 output,
5626 device,
5627 delayMs,
5628 force);
5629 }
5630}
5631
Eric Laurente0720872014-03-11 09:30:41 -07005632void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005633 bool on,
5634 audio_io_handle_t output,
5635 int delayMs,
5636 audio_devices_t device)
5637{
5638 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005639 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005640 if (stream == AUDIO_STREAM_PATCH) {
5641 continue;
5642 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005643 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5644 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005645 }
5646 }
5647}
5648
Eric Laurente0720872014-03-11 09:30:41 -07005649void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005650 bool on,
5651 audio_io_handle_t output,
5652 int delayMs,
5653 audio_devices_t device)
5654{
5655 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005656 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005657 if (device == AUDIO_DEVICE_NONE) {
5658 device = outputDesc->device();
5659 }
5660
5661 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5662 stream, on, output, outputDesc->mMuteCount[stream], device);
5663
5664 if (on) {
5665 if (outputDesc->mMuteCount[stream] == 0) {
5666 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005667 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5668 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005669 checkAndSetVolume(stream, 0, output, device, delayMs);
5670 }
5671 }
5672 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5673 outputDesc->mMuteCount[stream]++;
5674 } else {
5675 if (outputDesc->mMuteCount[stream] == 0) {
5676 ALOGV("setStreamMute() unmuting non muted stream!");
5677 return;
5678 }
5679 if (--outputDesc->mMuteCount[stream] == 0) {
5680 checkAndSetVolume(stream,
5681 streamDesc.getVolumeIndex(device),
5682 output,
5683 device,
5684 delayMs);
5685 }
5686 }
5687}
5688
Eric Laurente0720872014-03-11 09:30:41 -07005689void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005690 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005691{
5692 // if the stream pertains to sonification strategy and we are in call we must
5693 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5694 // in the device used for phone strategy and play the tone if the selected device does not
5695 // interfere with the device used for phone strategy
5696 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5697 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005698 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005699 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5700 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005701 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005702 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5703 stream, starting, outputDesc->mDevice, stateChange);
5704 if (outputDesc->mRefCount[stream]) {
5705 int muteCount = 1;
5706 if (stateChange) {
5707 muteCount = outputDesc->mRefCount[stream];
5708 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005709 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005710 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5711 for (int i = 0; i < muteCount; i++) {
5712 setStreamMute(stream, starting, mPrimaryOutput);
5713 }
5714 } else {
5715 ALOGV("handleIncallSonification() high visibility");
5716 if (outputDesc->device() &
5717 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5718 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5719 for (int i = 0; i < muteCount; i++) {
5720 setStreamMute(stream, starting, mPrimaryOutput);
5721 }
5722 }
5723 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005724 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5725 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005726 } else {
5727 mpClientInterface->stopTone();
5728 }
5729 }
5730 }
5731 }
5732}
5733
Eric Laurente0720872014-03-11 09:30:41 -07005734bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005735{
5736 return isStateInCall(mPhoneState);
5737}
5738
Eric Laurente0720872014-03-11 09:30:41 -07005739bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005740 return ((state == AUDIO_MODE_IN_CALL) ||
5741 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005742}
5743
Eric Laurente0720872014-03-11 09:30:41 -07005744uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005745{
5746 return MAX_EFFECTS_CPU_LOAD;
5747}
5748
Eric Laurente0720872014-03-11 09:30:41 -07005749uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005750{
5751 return MAX_EFFECTS_MEMORY;
5752}
5753
Eric Laurent6a94d692014-05-20 11:18:06 -07005754
Eric Laurente552edb2014-03-10 17:42:56 -07005755// --- AudioOutputDescriptor class implementation
5756
Eric Laurente0720872014-03-11 09:30:41 -07005757AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005758 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005759 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent275e8e92014-11-30 15:14:47 -08005760 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPolicyMixAddress(String8("")),
5761 mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005762 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5763{
5764 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005765 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005766 mRefCount[i] = 0;
5767 mCurVolume[i] = -1.0;
5768 mMuteCount[i] = 0;
5769 mStopTime[i] = 0;
5770 }
5771 for (int i = 0; i < NUM_STRATEGIES; i++) {
5772 mStrategyMutedByDevice[i] = false;
5773 }
5774 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005775 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005776 mSamplingRate = profile->pickSamplingRate();
5777 mFormat = profile->pickFormat();
5778 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005779 if (profile->mGains.size() > 0) {
5780 profile->mGains[0]->getDefaultConfig(&mGain);
5781 }
Eric Laurente552edb2014-03-10 17:42:56 -07005782 }
5783}
5784
Eric Laurente0720872014-03-11 09:30:41 -07005785audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005786{
5787 if (isDuplicated()) {
5788 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5789 } else {
5790 return mDevice;
5791 }
5792}
5793
Eric Laurente0720872014-03-11 09:30:41 -07005794uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005795{
5796 if (isDuplicated()) {
5797 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5798 } else {
5799 return mLatency;
5800 }
5801}
5802
Eric Laurente0720872014-03-11 09:30:41 -07005803bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005804 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005805{
5806 if (isDuplicated()) {
5807 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5808 } else if (outputDesc->isDuplicated()){
5809 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5810 } else {
5811 return (mProfile->mModule == outputDesc->mProfile->mModule);
5812 }
5813}
5814
Eric Laurente0720872014-03-11 09:30:41 -07005815void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005816 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005817{
5818 // forward usage count change to attached outputs
5819 if (isDuplicated()) {
5820 mOutput1->changeRefCount(stream, delta);
5821 mOutput2->changeRefCount(stream, delta);
5822 }
5823 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005824 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5825 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005826 mRefCount[stream] = 0;
5827 return;
5828 }
5829 mRefCount[stream] += delta;
5830 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5831}
5832
Eric Laurente0720872014-03-11 09:30:41 -07005833audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005834{
5835 if (isDuplicated()) {
5836 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5837 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005838 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005839 }
5840}
5841
Eric Laurente0720872014-03-11 09:30:41 -07005842bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005843{
5844 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5845}
5846
Eric Laurente0720872014-03-11 09:30:41 -07005847bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005848 uint32_t inPastMs,
5849 nsecs_t sysTime) const
5850{
5851 if ((sysTime == 0) && (inPastMs != 0)) {
5852 sysTime = systemTime();
5853 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005854 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005855 if (i == AUDIO_STREAM_PATCH) {
5856 continue;
5857 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005858 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005859 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005860 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005861 return true;
5862 }
5863 }
5864 return false;
5865}
5866
Eric Laurente0720872014-03-11 09:30:41 -07005867bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005868 uint32_t inPastMs,
5869 nsecs_t sysTime) const
5870{
5871 if (mRefCount[stream] != 0) {
5872 return true;
5873 }
5874 if (inPastMs == 0) {
5875 return false;
5876 }
5877 if (sysTime == 0) {
5878 sysTime = systemTime();
5879 }
5880 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5881 return true;
5882 }
5883 return false;
5884}
5885
Eric Laurent1c333e22014-05-20 10:48:17 -07005886void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005887 struct audio_port_config *dstConfig,
5888 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005889{
Eric Laurent84c70242014-06-23 08:46:27 -07005890 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5891
Eric Laurent1f2f2232014-06-02 12:01:23 -07005892 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5893 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5894 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005895 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005896 }
5897 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5898
Eric Laurent6a94d692014-05-20 11:18:06 -07005899 dstConfig->id = mId;
5900 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5901 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005902 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5903 dstConfig->ext.mix.handle = mIoHandle;
5904 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005905}
5906
5907void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5908 struct audio_port *port) const
5909{
Eric Laurent84c70242014-06-23 08:46:27 -07005910 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005911 mProfile->toAudioPort(port);
5912 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005913 toAudioPortConfig(&port->active_config);
5914 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005915 port->ext.mix.handle = mIoHandle;
5916 port->ext.mix.latency_class =
5917 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5918}
Eric Laurente552edb2014-03-10 17:42:56 -07005919
Eric Laurente0720872014-03-11 09:30:41 -07005920status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005921{
5922 const size_t SIZE = 256;
5923 char buffer[SIZE];
5924 String8 result;
5925
Eric Laurent4d416952014-08-10 14:07:09 -07005926 snprintf(buffer, SIZE, " ID: %d\n", mId);
5927 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005928 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5929 result.append(buffer);
5930 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5931 result.append(buffer);
5932 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5933 result.append(buffer);
5934 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5935 result.append(buffer);
5936 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5937 result.append(buffer);
5938 snprintf(buffer, SIZE, " Devices %08x\n", device());
5939 result.append(buffer);
5940 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5941 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005942 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5943 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5944 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005945 result.append(buffer);
5946 }
5947 write(fd, result.string(), result.size());
5948
5949 return NO_ERROR;
5950}
5951
5952// --- AudioInputDescriptor class implementation
5953
Eric Laurent1c333e22014-05-20 10:48:17 -07005954AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005955 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005956 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005957 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005958{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005959 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005960 mSamplingRate = profile->pickSamplingRate();
5961 mFormat = profile->pickFormat();
5962 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005963 if (profile->mGains.size() > 0) {
5964 profile->mGains[0]->getDefaultConfig(&mGain);
5965 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005966 }
Eric Laurente552edb2014-03-10 17:42:56 -07005967}
5968
Eric Laurent1c333e22014-05-20 10:48:17 -07005969void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005970 struct audio_port_config *dstConfig,
5971 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005972{
Eric Laurent84c70242014-06-23 08:46:27 -07005973 ALOG_ASSERT(mProfile != 0,
5974 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005975 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5976 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5977 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005978 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005979 }
5980
5981 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5982
Eric Laurent6a94d692014-05-20 11:18:06 -07005983 dstConfig->id = mId;
5984 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5985 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005986 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5987 dstConfig->ext.mix.handle = mIoHandle;
5988 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005989}
5990
5991void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5992 struct audio_port *port) const
5993{
Eric Laurent84c70242014-06-23 08:46:27 -07005994 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5995
Eric Laurent1c333e22014-05-20 10:48:17 -07005996 mProfile->toAudioPort(port);
5997 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005998 toAudioPortConfig(&port->active_config);
5999 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006000 port->ext.mix.handle = mIoHandle;
6001 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
6002}
6003
Eric Laurente0720872014-03-11 09:30:41 -07006004status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006005{
6006 const size_t SIZE = 256;
6007 char buffer[SIZE];
6008 String8 result;
6009
Eric Laurent4d416952014-08-10 14:07:09 -07006010 snprintf(buffer, SIZE, " ID: %d\n", mId);
6011 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006012 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6013 result.append(buffer);
6014 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
6015 result.append(buffer);
6016 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6017 result.append(buffer);
6018 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
6019 result.append(buffer);
6020 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
6021 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07006022 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
6023 result.append(buffer);
6024
Eric Laurente552edb2014-03-10 17:42:56 -07006025 write(fd, result.string(), result.size());
6026
6027 return NO_ERROR;
6028}
6029
6030// --- StreamDescriptor class implementation
6031
Eric Laurente0720872014-03-11 09:30:41 -07006032AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07006033 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
6034{
6035 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
6036}
6037
Eric Laurente0720872014-03-11 09:30:41 -07006038int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07006039{
Eric Laurente0720872014-03-11 09:30:41 -07006040 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07006041 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
6042 if (mIndexCur.indexOfKey(device) < 0) {
6043 device = AUDIO_DEVICE_OUT_DEFAULT;
6044 }
6045 return mIndexCur.valueFor(device);
6046}
6047
Eric Laurente0720872014-03-11 09:30:41 -07006048void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006049{
6050 const size_t SIZE = 256;
6051 char buffer[SIZE];
6052 String8 result;
6053
6054 snprintf(buffer, SIZE, "%s %02d %02d ",
6055 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
6056 result.append(buffer);
6057 for (size_t i = 0; i < mIndexCur.size(); i++) {
6058 snprintf(buffer, SIZE, "%04x : %02d, ",
6059 mIndexCur.keyAt(i),
6060 mIndexCur.valueAt(i));
6061 result.append(buffer);
6062 }
6063 result.append("\n");
6064
6065 write(fd, result.string(), result.size());
6066}
6067
6068// --- EffectDescriptor class implementation
6069
Eric Laurente0720872014-03-11 09:30:41 -07006070status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006071{
6072 const size_t SIZE = 256;
6073 char buffer[SIZE];
6074 String8 result;
6075
6076 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
6077 result.append(buffer);
6078 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
6079 result.append(buffer);
6080 snprintf(buffer, SIZE, " Session: %d\n", mSession);
6081 result.append(buffer);
6082 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
6083 result.append(buffer);
6084 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
6085 result.append(buffer);
6086 write(fd, result.string(), result.size());
6087
6088 return NO_ERROR;
6089}
6090
Eric Laurent1c333e22014-05-20 10:48:17 -07006091// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006092
Eric Laurente0720872014-03-11 09:30:41 -07006093AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07006094 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
6095 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07006096{
6097}
6098
Eric Laurente0720872014-03-11 09:30:41 -07006099AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07006100{
6101 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006102 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006103 }
6104 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006105 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006106 }
6107 free((void *)mName);
6108}
6109
Eric Laurent1afeecb2014-05-14 08:52:28 -07006110status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
6111{
6112 cnode *node = root->first_child;
6113
6114 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
6115
6116 while (node) {
6117 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6118 profile->loadSamplingRates((char *)node->value);
6119 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6120 profile->loadFormats((char *)node->value);
6121 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6122 profile->loadInChannels((char *)node->value);
6123 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6124 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6125 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07006126 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
6127 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006128 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6129 profile->loadGains(node);
6130 }
6131 node = node->next;
6132 }
6133 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6134 "loadInput() invalid supported devices");
6135 ALOGW_IF(profile->mChannelMasks.size() == 0,
6136 "loadInput() invalid supported channel masks");
6137 ALOGW_IF(profile->mSamplingRates.size() == 0,
6138 "loadInput() invalid supported sampling rates");
6139 ALOGW_IF(profile->mFormats.size() == 0,
6140 "loadInput() invalid supported formats");
6141 if (!profile->mSupportedDevices.isEmpty() &&
6142 (profile->mChannelMasks.size() != 0) &&
6143 (profile->mSamplingRates.size() != 0) &&
6144 (profile->mFormats.size() != 0)) {
6145
6146 ALOGV("loadInput() adding input Supported Devices %04x",
6147 profile->mSupportedDevices.types());
6148
6149 mInputProfiles.add(profile);
6150 return NO_ERROR;
6151 } else {
6152 return BAD_VALUE;
6153 }
6154}
6155
6156status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
6157{
6158 cnode *node = root->first_child;
6159
6160 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
6161
6162 while (node) {
6163 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6164 profile->loadSamplingRates((char *)node->value);
6165 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6166 profile->loadFormats((char *)node->value);
6167 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6168 profile->loadOutChannels((char *)node->value);
6169 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6170 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6171 mDeclaredDevices);
6172 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07006173 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006174 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6175 profile->loadGains(node);
6176 }
6177 node = node->next;
6178 }
6179 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6180 "loadOutput() invalid supported devices");
6181 ALOGW_IF(profile->mChannelMasks.size() == 0,
6182 "loadOutput() invalid supported channel masks");
6183 ALOGW_IF(profile->mSamplingRates.size() == 0,
6184 "loadOutput() invalid supported sampling rates");
6185 ALOGW_IF(profile->mFormats.size() == 0,
6186 "loadOutput() invalid supported formats");
6187 if (!profile->mSupportedDevices.isEmpty() &&
6188 (profile->mChannelMasks.size() != 0) &&
6189 (profile->mSamplingRates.size() != 0) &&
6190 (profile->mFormats.size() != 0)) {
6191
6192 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
6193 profile->mSupportedDevices.types(), profile->mFlags);
6194
6195 mOutputProfiles.add(profile);
6196 return NO_ERROR;
6197 } else {
6198 return BAD_VALUE;
6199 }
6200}
6201
6202status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
6203{
6204 cnode *node = root->first_child;
6205
6206 audio_devices_t type = AUDIO_DEVICE_NONE;
6207 while (node) {
6208 if (strcmp(node->name, DEVICE_TYPE) == 0) {
6209 type = parseDeviceNames((char *)node->value);
6210 break;
6211 }
6212 node = node->next;
6213 }
6214 if (type == AUDIO_DEVICE_NONE ||
6215 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
6216 ALOGW("loadDevice() bad type %08x", type);
6217 return BAD_VALUE;
6218 }
6219 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
6220 deviceDesc->mModule = this;
6221
6222 node = root->first_child;
6223 while (node) {
6224 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
6225 deviceDesc->mAddress = String8((char *)node->value);
6226 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6227 if (audio_is_input_device(type)) {
6228 deviceDesc->loadInChannels((char *)node->value);
6229 } else {
6230 deviceDesc->loadOutChannels((char *)node->value);
6231 }
6232 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6233 deviceDesc->loadGains(node);
6234 }
6235 node = node->next;
6236 }
6237
6238 ALOGV("loadDevice() adding device name %s type %08x address %s",
6239 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6240
6241 mDeclaredDevices.add(deviceDesc);
6242
6243 return NO_ERROR;
6244}
6245
Eric Laurent275e8e92014-11-30 15:14:47 -08006246status_t AudioPolicyManager::HwModule::addOutputProfile(String8 name, const audio_config_t *config,
6247 audio_devices_t device, String8 address)
6248{
6249 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SOURCE, this);
6250
6251 profile->mSamplingRates.add(config->sample_rate);
6252 profile->mChannelMasks.add(config->channel_mask);
6253 profile->mFormats.add(config->format);
6254
6255 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6256 devDesc->mAddress = address;
6257 profile->mSupportedDevices.add(devDesc);
6258
6259 mOutputProfiles.add(profile);
6260
6261 return NO_ERROR;
6262}
6263
6264status_t AudioPolicyManager::HwModule::removeOutputProfile(String8 name)
6265{
6266 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
6267 if (mOutputProfiles[i]->mName == name) {
6268 mOutputProfiles.removeAt(i);
6269 break;
6270 }
6271 }
6272
6273 return NO_ERROR;
6274}
6275
6276status_t AudioPolicyManager::HwModule::addInputProfile(String8 name, const audio_config_t *config,
6277 audio_devices_t device, String8 address)
6278{
6279 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SINK, this);
6280
6281 profile->mSamplingRates.add(config->sample_rate);
6282 profile->mChannelMasks.add(config->channel_mask);
6283 profile->mFormats.add(config->format);
6284
6285 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6286 devDesc->mAddress = address;
6287 profile->mSupportedDevices.add(devDesc);
6288
6289 ALOGV("addInputProfile() name %s rate %d mask 0x08", name.string(), config->sample_rate, config->channel_mask);
6290
6291 mInputProfiles.add(profile);
6292
6293 return NO_ERROR;
6294}
6295
6296status_t AudioPolicyManager::HwModule::removeInputProfile(String8 name)
6297{
6298 for (size_t i = 0; i < mInputProfiles.size(); i++) {
6299 if (mInputProfiles[i]->mName == name) {
6300 mInputProfiles.removeAt(i);
6301 break;
6302 }
6303 }
6304
6305 return NO_ERROR;
6306}
6307
6308
Eric Laurente0720872014-03-11 09:30:41 -07006309void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006310{
6311 const size_t SIZE = 256;
6312 char buffer[SIZE];
6313 String8 result;
6314
6315 snprintf(buffer, SIZE, " - name: %s\n", mName);
6316 result.append(buffer);
6317 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6318 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006319 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6320 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006321 write(fd, result.string(), result.size());
6322 if (mOutputProfiles.size()) {
6323 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6324 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006325 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006326 write(fd, buffer, strlen(buffer));
6327 mOutputProfiles[i]->dump(fd);
6328 }
6329 }
6330 if (mInputProfiles.size()) {
6331 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6332 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006333 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006334 write(fd, buffer, strlen(buffer));
6335 mInputProfiles[i]->dump(fd);
6336 }
6337 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006338 if (mDeclaredDevices.size()) {
6339 write(fd, " - devices:\n", strlen(" - devices:\n"));
6340 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6341 mDeclaredDevices[i]->dump(fd, 4, i);
6342 }
6343 }
Eric Laurente552edb2014-03-10 17:42:56 -07006344}
6345
Eric Laurent1c333e22014-05-20 10:48:17 -07006346// --- AudioPort class implementation
6347
Eric Laurenta121f902014-06-03 13:32:54 -07006348
6349AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6350 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07006351 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006352{
6353 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6354 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6355}
6356
Eric Laurent1c333e22014-05-20 10:48:17 -07006357void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6358{
6359 port->role = mRole;
6360 port->type = mType;
6361 unsigned int i;
6362 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006363 if (mSamplingRates[i] != 0) {
6364 port->sample_rates[i] = mSamplingRates[i];
6365 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006366 }
6367 port->num_sample_rates = i;
6368 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006369 if (mChannelMasks[i] != 0) {
6370 port->channel_masks[i] = mChannelMasks[i];
6371 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006372 }
6373 port->num_channel_masks = i;
6374 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006375 if (mFormats[i] != 0) {
6376 port->formats[i] = mFormats[i];
6377 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006378 }
6379 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006380
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006381 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006382
6383 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6384 port->gains[i] = mGains[i]->mGain;
6385 }
6386 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006387}
6388
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006389void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6390 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6391 const uint32_t rate = port->mSamplingRates.itemAt(k);
6392 if (rate != 0) { // skip "dynamic" rates
6393 bool hasRate = false;
6394 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6395 if (rate == mSamplingRates.itemAt(l)) {
6396 hasRate = true;
6397 break;
6398 }
6399 }
6400 if (!hasRate) { // never import a sampling rate twice
6401 mSamplingRates.add(rate);
6402 }
6403 }
6404 }
6405 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6406 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6407 if (mask != 0) { // skip "dynamic" masks
6408 bool hasMask = false;
6409 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6410 if (mask == mChannelMasks.itemAt(l)) {
6411 hasMask = true;
6412 break;
6413 }
6414 }
6415 if (!hasMask) { // never import a channel mask twice
6416 mChannelMasks.add(mask);
6417 }
6418 }
6419 }
6420 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6421 const audio_format_t format = port->mFormats.itemAt(k);
6422 if (format != 0) { // skip "dynamic" formats
6423 bool hasFormat = false;
6424 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6425 if (format == mFormats.itemAt(l)) {
6426 hasFormat = true;
6427 break;
6428 }
6429 }
6430 if (!hasFormat) { // never import a channel mask twice
6431 mFormats.add(format);
6432 }
6433 }
6434 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006435 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6436 sp<AudioGain> gain = port->mGains.itemAt(k);
6437 if (gain != 0) {
6438 bool hasGain = false;
6439 for (size_t l = 0 ; l < mGains.size() ; l++) {
6440 if (gain == mGains.itemAt(l)) {
6441 hasGain = true;
6442 break;
6443 }
6444 }
6445 if (!hasGain) { // never import a gain twice
6446 mGains.add(gain);
6447 }
6448 }
6449 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006450}
6451
6452void AudioPolicyManager::AudioPort::clearCapabilities() {
6453 mChannelMasks.clear();
6454 mFormats.clear();
6455 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006456 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006457}
Eric Laurent1c333e22014-05-20 10:48:17 -07006458
6459void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6460{
6461 char *str = strtok(name, "|");
6462
6463 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6464 // rates should be read from the output stream after it is opened for the first time
6465 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6466 mSamplingRates.add(0);
6467 return;
6468 }
6469
6470 while (str != NULL) {
6471 uint32_t rate = atoi(str);
6472 if (rate != 0) {
6473 ALOGV("loadSamplingRates() adding rate %d", rate);
6474 mSamplingRates.add(rate);
6475 }
6476 str = strtok(NULL, "|");
6477 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006478}
6479
6480void AudioPolicyManager::AudioPort::loadFormats(char *name)
6481{
6482 char *str = strtok(name, "|");
6483
6484 // by convention, "0' in the first entry in mFormats indicates the supported formats
6485 // should be read from the output stream after it is opened for the first time
6486 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6487 mFormats.add(AUDIO_FORMAT_DEFAULT);
6488 return;
6489 }
6490
6491 while (str != NULL) {
6492 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6493 ARRAY_SIZE(sFormatNameToEnumTable),
6494 str);
6495 if (format != AUDIO_FORMAT_DEFAULT) {
6496 mFormats.add(format);
6497 }
6498 str = strtok(NULL, "|");
6499 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006500}
6501
6502void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6503{
6504 const char *str = strtok(name, "|");
6505
6506 ALOGV("loadInChannels() %s", name);
6507
6508 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6509 mChannelMasks.add(0);
6510 return;
6511 }
6512
6513 while (str != NULL) {
6514 audio_channel_mask_t channelMask =
6515 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6516 ARRAY_SIZE(sInChannelsNameToEnumTable),
6517 str);
6518 if (channelMask != 0) {
6519 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6520 mChannelMasks.add(channelMask);
6521 }
6522 str = strtok(NULL, "|");
6523 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006524}
6525
6526void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6527{
6528 const char *str = strtok(name, "|");
6529
6530 ALOGV("loadOutChannels() %s", name);
6531
6532 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6533 // masks should be read from the output stream after it is opened for the first time
6534 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6535 mChannelMasks.add(0);
6536 return;
6537 }
6538
6539 while (str != NULL) {
6540 audio_channel_mask_t channelMask =
6541 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6542 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6543 str);
6544 if (channelMask != 0) {
6545 mChannelMasks.add(channelMask);
6546 }
6547 str = strtok(NULL, "|");
6548 }
6549 return;
6550}
6551
Eric Laurent1afeecb2014-05-14 08:52:28 -07006552audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6553{
6554 const char *str = strtok(name, "|");
6555
6556 ALOGV("loadGainMode() %s", name);
6557 audio_gain_mode_t mode = 0;
6558 while (str != NULL) {
6559 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6560 ARRAY_SIZE(sGainModeNameToEnumTable),
6561 str);
6562 str = strtok(NULL, "|");
6563 }
6564 return mode;
6565}
6566
Eric Laurenta121f902014-06-03 13:32:54 -07006567void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006568{
6569 cnode *node = root->first_child;
6570
Eric Laurenta121f902014-06-03 13:32:54 -07006571 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006572
6573 while (node) {
6574 if (strcmp(node->name, GAIN_MODE) == 0) {
6575 gain->mGain.mode = loadGainMode((char *)node->value);
6576 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006577 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006578 gain->mGain.channel_mask =
6579 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6580 ARRAY_SIZE(sInChannelsNameToEnumTable),
6581 (char *)node->value);
6582 } else {
6583 gain->mGain.channel_mask =
6584 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6585 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6586 (char *)node->value);
6587 }
6588 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6589 gain->mGain.min_value = atoi((char *)node->value);
6590 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6591 gain->mGain.max_value = atoi((char *)node->value);
6592 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6593 gain->mGain.default_value = atoi((char *)node->value);
6594 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6595 gain->mGain.step_value = atoi((char *)node->value);
6596 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6597 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6598 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6599 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6600 }
6601 node = node->next;
6602 }
6603
6604 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6605 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6606
6607 if (gain->mGain.mode == 0) {
6608 return;
6609 }
6610 mGains.add(gain);
6611}
6612
6613void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6614{
6615 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006616 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006617 while (node) {
6618 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006619 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006620 node = node->next;
6621 }
6622}
6623
Glenn Kastencbd48022014-07-24 13:46:44 -07006624status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006625{
Eric Laurent0daea392014-12-04 19:14:54 -08006626 if (mSamplingRates.isEmpty()) {
6627 return NO_ERROR;
6628 }
6629
Eric Laurenta121f902014-06-03 13:32:54 -07006630 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6631 if (mSamplingRates[i] == samplingRate) {
6632 return NO_ERROR;
6633 }
6634 }
6635 return BAD_VALUE;
6636}
6637
Glenn Kastencbd48022014-07-24 13:46:44 -07006638status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6639 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006640{
Eric Laurent0daea392014-12-04 19:14:54 -08006641 if (mSamplingRates.isEmpty()) {
6642 return NO_ERROR;
6643 }
6644
Glenn Kastencbd48022014-07-24 13:46:44 -07006645 // Search for the closest supported sampling rate that is above (preferred)
6646 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6647 // The sampling rates do not need to be sorted in ascending order.
6648 ssize_t maxBelow = -1;
6649 ssize_t minAbove = -1;
6650 uint32_t candidate;
6651 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6652 candidate = mSamplingRates[i];
6653 if (candidate == samplingRate) {
6654 if (updatedSamplingRate != NULL) {
6655 *updatedSamplingRate = candidate;
6656 }
6657 return NO_ERROR;
6658 }
6659 // candidate < desired
6660 if (candidate < samplingRate) {
6661 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6662 maxBelow = i;
6663 }
6664 // candidate > desired
6665 } else {
6666 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6667 minAbove = i;
6668 }
6669 }
6670 }
6671 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6672 // TODO Move these assumptions out.
6673 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6674 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6675 // due to approximation by an int32_t of the
6676 // phase increments
6677 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6678 if (minAbove >= 0) {
6679 candidate = mSamplingRates[minAbove];
6680 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6681 if (updatedSamplingRate != NULL) {
6682 *updatedSamplingRate = candidate;
6683 }
6684 return NO_ERROR;
6685 }
6686 }
6687 // But if we have to up-sample from a lower sampling rate, that's OK.
6688 if (maxBelow >= 0) {
6689 candidate = mSamplingRates[maxBelow];
6690 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6691 if (updatedSamplingRate != NULL) {
6692 *updatedSamplingRate = candidate;
6693 }
6694 return NO_ERROR;
6695 }
6696 }
6697 // leave updatedSamplingRate unmodified
6698 return BAD_VALUE;
6699}
6700
6701status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6702{
Eric Laurent0daea392014-12-04 19:14:54 -08006703 if (mChannelMasks.isEmpty()) {
6704 return NO_ERROR;
6705 }
6706
Glenn Kastencbd48022014-07-24 13:46:44 -07006707 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006708 if (mChannelMasks[i] == channelMask) {
6709 return NO_ERROR;
6710 }
6711 }
6712 return BAD_VALUE;
6713}
6714
Glenn Kastencbd48022014-07-24 13:46:44 -07006715status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6716 const
6717{
Eric Laurent0daea392014-12-04 19:14:54 -08006718 if (mChannelMasks.isEmpty()) {
6719 return NO_ERROR;
6720 }
6721
Glenn Kastencbd48022014-07-24 13:46:44 -07006722 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6723 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6724 // FIXME Does not handle multi-channel automatic conversions yet
6725 audio_channel_mask_t supported = mChannelMasks[i];
6726 if (supported == channelMask) {
6727 return NO_ERROR;
6728 }
6729 if (isRecordThread) {
6730 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6731 // FIXME Abstract this out to a table.
6732 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6733 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6734 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6735 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6736 return NO_ERROR;
6737 }
6738 }
6739 }
6740 return BAD_VALUE;
6741}
6742
Eric Laurenta121f902014-06-03 13:32:54 -07006743status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6744{
Eric Laurent0daea392014-12-04 19:14:54 -08006745 if (mFormats.isEmpty()) {
6746 return NO_ERROR;
6747 }
6748
Eric Laurenta121f902014-06-03 13:32:54 -07006749 for (size_t i = 0; i < mFormats.size(); i ++) {
6750 if (mFormats[i] == format) {
6751 return NO_ERROR;
6752 }
6753 }
6754 return BAD_VALUE;
6755}
6756
Eric Laurent1e693b52014-07-09 15:03:28 -07006757
6758uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6759{
6760 // special case for uninitialized dynamic profile
6761 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6762 return 0;
6763 }
6764
Eric Laurent828bcff2014-09-07 12:26:06 -07006765 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6766 // channel count / sampling rate combination chosen will be supported by the connected
6767 // sink
6768 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6769 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6770 uint32_t samplingRate = UINT_MAX;
6771 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6772 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6773 samplingRate = mSamplingRates[i];
6774 }
6775 }
6776 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6777 }
6778
Eric Laurent1e693b52014-07-09 15:03:28 -07006779 uint32_t samplingRate = 0;
6780 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6781
6782 // For mixed output and inputs, use max mixer sampling rates. Do not
6783 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006784 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006785 maxRate = UINT_MAX;
6786 }
6787 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6788 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6789 samplingRate = mSamplingRates[i];
6790 }
6791 }
6792 return samplingRate;
6793}
6794
6795audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6796{
6797 // special case for uninitialized dynamic profile
6798 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6799 return AUDIO_CHANNEL_NONE;
6800 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006801 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006802
6803 // For direct outputs, pick minimum channel count: this helps ensuring that the
6804 // channel count / sampling rate combination chosen will be supported by the connected
6805 // sink
6806 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6807 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6808 uint32_t channelCount = UINT_MAX;
6809 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6810 uint32_t cnlCount;
6811 if (mUseInChannelMask) {
6812 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6813 } else {
6814 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6815 }
6816 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6817 channelMask = mChannelMasks[i];
6818 channelCount = cnlCount;
6819 }
6820 }
6821 return channelMask;
6822 }
6823
Eric Laurent1e693b52014-07-09 15:03:28 -07006824 uint32_t channelCount = 0;
6825 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6826
6827 // For mixed output and inputs, use max mixer channel count. Do not
6828 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006829 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006830 maxCount = UINT_MAX;
6831 }
6832 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6833 uint32_t cnlCount;
6834 if (mUseInChannelMask) {
6835 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6836 } else {
6837 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6838 }
6839 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6840 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006841 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006842 }
6843 }
6844 return channelMask;
6845}
6846
Andy Hung9a605382014-07-28 16:16:31 -07006847/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006848const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6849 AUDIO_FORMAT_DEFAULT,
6850 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006851 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006852 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006853 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006854 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006855};
6856
6857int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6858 audio_format_t format2)
6859{
6860 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6861 // compressed format and better than any PCM format. This is by design of pickFormat()
6862 if (!audio_is_linear_pcm(format1)) {
6863 if (!audio_is_linear_pcm(format2)) {
6864 return 0;
6865 }
6866 return 1;
6867 }
6868 if (!audio_is_linear_pcm(format2)) {
6869 return -1;
6870 }
6871
6872 int index1 = -1, index2 = -1;
6873 for (size_t i = 0;
6874 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6875 i ++) {
6876 if (sPcmFormatCompareTable[i] == format1) {
6877 index1 = i;
6878 }
6879 if (sPcmFormatCompareTable[i] == format2) {
6880 index2 = i;
6881 }
6882 }
6883 // format1 not found => index1 < 0 => format2 > format1
6884 // format2 not found => index2 < 0 => format2 < format1
6885 return index1 - index2;
6886}
6887
6888audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6889{
6890 // special case for uninitialized dynamic profile
6891 if (mFormats.size() == 1 && mFormats[0] == 0) {
6892 return AUDIO_FORMAT_DEFAULT;
6893 }
6894
6895 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006896 audio_format_t bestFormat =
6897 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6898 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006899 // For mixed output and inputs, use best mixer output format. Do not
6900 // limit format otherwise
6901 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6902 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006903 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006904 bestFormat = AUDIO_FORMAT_INVALID;
6905 }
6906
6907 for (size_t i = 0; i < mFormats.size(); i ++) {
6908 if ((compareFormats(mFormats[i], format) > 0) &&
6909 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6910 format = mFormats[i];
6911 }
6912 }
6913 return format;
6914}
6915
Eric Laurenta121f902014-06-03 13:32:54 -07006916status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6917 int index) const
6918{
6919 if (index < 0 || (size_t)index >= mGains.size()) {
6920 return BAD_VALUE;
6921 }
6922 return mGains[index]->checkConfig(gainConfig);
6923}
6924
Eric Laurent1afeecb2014-05-14 08:52:28 -07006925void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6926{
6927 const size_t SIZE = 256;
6928 char buffer[SIZE];
6929 String8 result;
6930
6931 if (mName.size() != 0) {
6932 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6933 result.append(buffer);
6934 }
6935
6936 if (mSamplingRates.size() != 0) {
6937 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6938 result.append(buffer);
6939 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006940 if (i == 0 && mSamplingRates[i] == 0) {
6941 snprintf(buffer, SIZE, "Dynamic");
6942 } else {
6943 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6944 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006945 result.append(buffer);
6946 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6947 }
6948 result.append("\n");
6949 }
6950
6951 if (mChannelMasks.size() != 0) {
6952 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6953 result.append(buffer);
6954 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006955 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6956
6957 if (i == 0 && mChannelMasks[i] == 0) {
6958 snprintf(buffer, SIZE, "Dynamic");
6959 } else {
6960 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6961 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006962 result.append(buffer);
6963 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6964 }
6965 result.append("\n");
6966 }
6967
6968 if (mFormats.size() != 0) {
6969 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6970 result.append(buffer);
6971 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006972 const char *formatStr = enumToString(sFormatNameToEnumTable,
6973 ARRAY_SIZE(sFormatNameToEnumTable),
6974 mFormats[i]);
6975 if (i == 0 && strcmp(formatStr, "") == 0) {
6976 snprintf(buffer, SIZE, "Dynamic");
6977 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006978 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006979 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006980 result.append(buffer);
6981 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6982 }
6983 result.append("\n");
6984 }
6985 write(fd, result.string(), result.size());
6986 if (mGains.size() != 0) {
6987 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6988 write(fd, buffer, strlen(buffer) + 1);
6989 result.append(buffer);
6990 for (size_t i = 0; i < mGains.size(); i++) {
6991 mGains[i]->dump(fd, spaces + 2, i);
6992 }
6993 }
6994}
6995
6996// --- AudioGain class implementation
6997
Eric Laurenta121f902014-06-03 13:32:54 -07006998AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006999{
Eric Laurenta121f902014-06-03 13:32:54 -07007000 mIndex = index;
7001 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007002 memset(&mGain, 0, sizeof(struct audio_gain));
7003}
7004
Eric Laurenta121f902014-06-03 13:32:54 -07007005void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
7006{
7007 config->index = mIndex;
7008 config->mode = mGain.mode;
7009 config->channel_mask = mGain.channel_mask;
7010 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7011 config->values[0] = mGain.default_value;
7012 } else {
7013 uint32_t numValues;
7014 if (mUseInChannelMask) {
7015 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
7016 } else {
7017 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
7018 }
7019 for (size_t i = 0; i < numValues; i++) {
7020 config->values[i] = mGain.default_value;
7021 }
7022 }
7023 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7024 config->ramp_duration_ms = mGain.min_ramp_ms;
7025 }
7026}
7027
7028status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
7029{
7030 if ((config->mode & ~mGain.mode) != 0) {
7031 return BAD_VALUE;
7032 }
7033 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7034 if ((config->values[0] < mGain.min_value) ||
7035 (config->values[0] > mGain.max_value)) {
7036 return BAD_VALUE;
7037 }
7038 } else {
7039 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
7040 return BAD_VALUE;
7041 }
7042 uint32_t numValues;
7043 if (mUseInChannelMask) {
7044 numValues = audio_channel_count_from_in_mask(config->channel_mask);
7045 } else {
7046 numValues = audio_channel_count_from_out_mask(config->channel_mask);
7047 }
7048 for (size_t i = 0; i < numValues; i++) {
7049 if ((config->values[i] < mGain.min_value) ||
7050 (config->values[i] > mGain.max_value)) {
7051 return BAD_VALUE;
7052 }
7053 }
7054 }
7055 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7056 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
7057 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
7058 return BAD_VALUE;
7059 }
7060 }
7061 return NO_ERROR;
7062}
7063
Eric Laurent1afeecb2014-05-14 08:52:28 -07007064void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
7065{
7066 const size_t SIZE = 256;
7067 char buffer[SIZE];
7068 String8 result;
7069
7070 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
7071 result.append(buffer);
7072 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
7073 result.append(buffer);
7074 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
7075 result.append(buffer);
7076 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
7077 result.append(buffer);
7078 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
7079 result.append(buffer);
7080 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
7081 result.append(buffer);
7082 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
7083 result.append(buffer);
7084 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
7085 result.append(buffer);
7086 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
7087 result.append(buffer);
7088
7089 write(fd, result.string(), result.size());
7090}
7091
Eric Laurent1f2f2232014-06-02 12:01:23 -07007092// --- AudioPortConfig class implementation
7093
7094AudioPolicyManager::AudioPortConfig::AudioPortConfig()
7095{
7096 mSamplingRate = 0;
7097 mChannelMask = AUDIO_CHANNEL_NONE;
7098 mFormat = AUDIO_FORMAT_INVALID;
7099 mGain.index = -1;
7100}
7101
Eric Laurenta121f902014-06-03 13:32:54 -07007102status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
7103 const struct audio_port_config *config,
7104 struct audio_port_config *backupConfig)
7105{
7106 struct audio_port_config localBackupConfig;
7107 status_t status = NO_ERROR;
7108
7109 localBackupConfig.config_mask = config->config_mask;
7110 toAudioPortConfig(&localBackupConfig);
7111
Marco Nelissen961ec212014-08-25 15:58:39 -07007112 sp<AudioPort> audioport = getAudioPort();
7113 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07007114 status = NO_INIT;
7115 goto exit;
7116 }
7117 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007118 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07007119 if (status != NO_ERROR) {
7120 goto exit;
7121 }
7122 mSamplingRate = config->sample_rate;
7123 }
7124 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007125 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07007126 if (status != NO_ERROR) {
7127 goto exit;
7128 }
7129 mChannelMask = config->channel_mask;
7130 }
7131 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007132 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07007133 if (status != NO_ERROR) {
7134 goto exit;
7135 }
7136 mFormat = config->format;
7137 }
7138 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007139 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07007140 if (status != NO_ERROR) {
7141 goto exit;
7142 }
7143 mGain = config->gain;
7144 }
7145
7146exit:
7147 if (status != NO_ERROR) {
7148 applyAudioPortConfig(&localBackupConfig);
7149 }
7150 if (backupConfig != NULL) {
7151 *backupConfig = localBackupConfig;
7152 }
7153 return status;
7154}
7155
Eric Laurent1f2f2232014-06-02 12:01:23 -07007156void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
7157 struct audio_port_config *dstConfig,
7158 const struct audio_port_config *srcConfig) const
7159{
7160 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
7161 dstConfig->sample_rate = mSamplingRate;
7162 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
7163 dstConfig->sample_rate = srcConfig->sample_rate;
7164 }
7165 } else {
7166 dstConfig->sample_rate = 0;
7167 }
7168 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
7169 dstConfig->channel_mask = mChannelMask;
7170 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
7171 dstConfig->channel_mask = srcConfig->channel_mask;
7172 }
7173 } else {
7174 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
7175 }
7176 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
7177 dstConfig->format = mFormat;
7178 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
7179 dstConfig->format = srcConfig->format;
7180 }
7181 } else {
7182 dstConfig->format = AUDIO_FORMAT_INVALID;
7183 }
7184 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
7185 dstConfig->gain = mGain;
7186 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
7187 dstConfig->gain = srcConfig->gain;
7188 }
7189 } else {
7190 dstConfig->gain.index = -1;
7191 }
7192 if (dstConfig->gain.index != -1) {
7193 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
7194 } else {
7195 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
7196 }
7197}
7198
Eric Laurent1c333e22014-05-20 10:48:17 -07007199// --- IOProfile class implementation
7200
Eric Laurent1afeecb2014-05-14 08:52:28 -07007201AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07007202 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07007203 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07007204{
7205}
7206
Eric Laurente0720872014-03-11 09:30:41 -07007207AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07007208{
7209}
7210
7211// checks if the IO profile is compatible with specified parameters.
7212// Sampling rate, format and channel mask must be specified in order to
7213// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07007214bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08007215 String8 address,
7216 uint32_t samplingRate,
7217 uint32_t *updatedSamplingRate,
7218 audio_format_t format,
7219 audio_channel_mask_t channelMask,
7220 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07007221{
Glenn Kastencbd48022014-07-24 13:46:44 -07007222 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
7223 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
7224 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07007225
Eric Laurent275e8e92014-11-30 15:14:47 -08007226 if (device != AUDIO_DEVICE_NONE && mSupportedDevices.getDevice(device, address) == 0) {
Glenn Kastencbd48022014-07-24 13:46:44 -07007227 return false;
7228 }
7229
7230 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07007231 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007232 }
7233 uint32_t myUpdatedSamplingRate = samplingRate;
7234 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007235 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007236 }
7237 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
7238 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007239 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007240 }
7241
7242 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
7243 return false;
7244 }
7245
7246 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
7247 checkExactChannelMask(channelMask) != NO_ERROR)) {
7248 return false;
7249 }
7250 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
7251 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
7252 return false;
7253 }
7254
7255 if (isPlaybackThread && (mFlags & flags) != flags) {
7256 return false;
7257 }
7258 // The only input flag that is allowed to be different is the fast flag.
7259 // An existing fast stream is compatible with a normal track request.
7260 // An existing normal stream is compatible with a fast track request,
7261 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07007262 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07007263 ~AUDIO_INPUT_FLAG_FAST)) {
7264 return false;
7265 }
7266
7267 if (updatedSamplingRate != NULL) {
7268 *updatedSamplingRate = myUpdatedSamplingRate;
7269 }
7270 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07007271}
7272
Eric Laurente0720872014-03-11 09:30:41 -07007273void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07007274{
7275 const size_t SIZE = 256;
7276 char buffer[SIZE];
7277 String8 result;
7278
Eric Laurent1afeecb2014-05-14 08:52:28 -07007279 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007280
Eric Laurente552edb2014-03-10 17:42:56 -07007281 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
7282 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007283 snprintf(buffer, SIZE, " - devices:\n");
7284 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07007285 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07007286 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
7287 mSupportedDevices[i]->dump(fd, 6, i);
7288 }
Eric Laurente552edb2014-03-10 17:42:56 -07007289}
7290
Eric Laurentd4692962014-05-05 18:13:44 -07007291void AudioPolicyManager::IOProfile::log()
7292{
7293 const size_t SIZE = 256;
7294 char buffer[SIZE];
7295 String8 result;
7296
7297 ALOGV(" - sampling rates: ");
7298 for (size_t i = 0; i < mSamplingRates.size(); i++) {
7299 ALOGV(" %d", mSamplingRates[i]);
7300 }
7301
7302 ALOGV(" - channel masks: ");
7303 for (size_t i = 0; i < mChannelMasks.size(); i++) {
7304 ALOGV(" 0x%04x", mChannelMasks[i]);
7305 }
7306
7307 ALOGV(" - formats: ");
7308 for (size_t i = 0; i < mFormats.size(); i++) {
7309 ALOGV(" 0x%08x", mFormats[i]);
7310 }
7311
7312 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
7313 ALOGV(" - flags: 0x%04x\n", mFlags);
7314}
7315
7316
Eric Laurent3a4311c2014-03-17 12:00:47 -07007317// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07007318
Eric Laurent1f2f2232014-06-02 12:01:23 -07007319
7320AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
7321 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7322 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7323 AUDIO_PORT_ROLE_SOURCE,
7324 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07007325 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07007326{
Eric Laurenta121f902014-06-03 13:32:54 -07007327 if (mGains.size() > 0) {
7328 mGains[0]->getDefaultConfig(&mGain);
7329 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07007330}
7331
Eric Laurent3a4311c2014-03-17 12:00:47 -07007332bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07007333{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007334 // Devices are considered equal if they:
7335 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7336 // - have the same address or one device does not specify the address
7337 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007338 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007339 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007340 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007341 mChannelMask == other->mChannelMask);
7342}
7343
7344void AudioPolicyManager::DeviceVector::refreshTypes()
7345{
Eric Laurent1c333e22014-05-20 10:48:17 -07007346 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007347 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007348 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007349 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007350 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007351}
7352
7353ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7354{
7355 for(size_t i = 0; i < size(); i++) {
7356 if (item->equals(itemAt(i))) {
7357 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007358 }
7359 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007360 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007361}
7362
Eric Laurent3a4311c2014-03-17 12:00:47 -07007363ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007364{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007365 ssize_t ret = indexOf(item);
7366
7367 if (ret < 0) {
7368 ret = SortedVector::add(item);
7369 if (ret >= 0) {
7370 refreshTypes();
7371 }
7372 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007373 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007374 ret = -1;
7375 }
7376 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007377}
7378
Eric Laurent3a4311c2014-03-17 12:00:47 -07007379ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7380{
7381 size_t i;
7382 ssize_t ret = indexOf(item);
7383
7384 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007385 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007386 } else {
7387 ret = SortedVector::removeAt(ret);
7388 if (ret >= 0) {
7389 refreshTypes();
7390 }
7391 }
7392 return ret;
7393}
7394
7395void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7396{
7397 DeviceVector deviceList;
7398
7399 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7400 types &= ~role_bit;
7401
7402 while (types) {
7403 uint32_t i = 31 - __builtin_clz(types);
7404 uint32_t type = 1 << i;
7405 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007406 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007407 }
7408}
7409
Eric Laurent1afeecb2014-05-14 08:52:28 -07007410void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7411 const DeviceVector& declaredDevices)
7412{
7413 char *devName = strtok(name, "|");
7414 while (devName != NULL) {
7415 if (strlen(devName) != 0) {
7416 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7417 ARRAY_SIZE(sDeviceNameToEnumTable),
7418 devName);
7419 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007420 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
Eric Laurent275e8e92014-11-30 15:14:47 -08007421 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX ||
7422 type == AUDIO_DEVICE_OUT_REMOTE_SUBMIX ) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007423 dev->mAddress = String8("0");
7424 }
7425 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007426 } else {
7427 sp<DeviceDescriptor> deviceDesc =
7428 declaredDevices.getDeviceFromName(String8(devName));
7429 if (deviceDesc != 0) {
7430 add(deviceDesc);
7431 }
7432 }
7433 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007434 devName = strtok(NULL, "|");
Eric Laurent1afeecb2014-05-14 08:52:28 -07007435 }
7436}
7437
Eric Laurent1c333e22014-05-20 10:48:17 -07007438sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7439 audio_devices_t type, String8 address) const
7440{
7441 sp<DeviceDescriptor> device;
7442 for (size_t i = 0; i < size(); i++) {
7443 if (itemAt(i)->mDeviceType == type) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007444 if (address == "" || itemAt(i)->mAddress == address) {
7445 device = itemAt(i);
7446 if (itemAt(i)->mAddress == address) {
7447 break;
7448 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007449 }
7450 }
7451 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007452 ALOGV("DeviceVector::getDevice() for type %08x address %s found %p",
Eric Laurent1c333e22014-05-20 10:48:17 -07007453 type, address.string(), device.get());
7454 return device;
7455}
7456
Eric Laurent6a94d692014-05-20 11:18:06 -07007457sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7458 audio_port_handle_t id) const
7459{
7460 sp<DeviceDescriptor> device;
7461 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007462 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007463 if (itemAt(i)->mId == id) {
7464 device = itemAt(i);
7465 break;
7466 }
7467 }
7468 return device;
7469}
7470
Eric Laurent1c333e22014-05-20 10:48:17 -07007471AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7472 audio_devices_t type) const
7473{
7474 DeviceVector devices;
7475 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7476 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7477 devices.add(itemAt(i));
7478 type &= ~itemAt(i)->mDeviceType;
7479 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7480 itemAt(i)->mDeviceType, itemAt(i).get());
7481 }
7482 }
7483 return devices;
7484}
7485
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007486AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7487 audio_devices_t type, String8 address) const
7488{
7489 DeviceVector devices;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007490 for (size_t i = 0; i < size(); i++) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007491 if (itemAt(i)->mDeviceType == type) {
7492 if (itemAt(i)->mAddress == address) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007493 devices.add(itemAt(i));
7494 }
7495 }
7496 }
7497 return devices;
7498}
7499
Eric Laurent1afeecb2014-05-14 08:52:28 -07007500sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7501 const String8& name) const
7502{
7503 sp<DeviceDescriptor> device;
7504 for (size_t i = 0; i < size(); i++) {
7505 if (itemAt(i)->mName == name) {
7506 device = itemAt(i);
7507 break;
7508 }
7509 }
7510 return device;
7511}
7512
Eric Laurent6a94d692014-05-20 11:18:06 -07007513void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7514 struct audio_port_config *dstConfig,
7515 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007516{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007517 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7518 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007519 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007520 }
7521
7522 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7523
Eric Laurent6a94d692014-05-20 11:18:06 -07007524 dstConfig->id = mId;
7525 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007526 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007527 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007528 dstConfig->ext.device.type = mDeviceType;
7529 dstConfig->ext.device.hw_module = mModule->mHandle;
7530 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007531}
7532
7533void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7534{
Eric Laurent83b88082014-06-20 18:31:16 -07007535 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007536 AudioPort::toAudioPort(port);
7537 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007538 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007539 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007540 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007541 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7542}
7543
Eric Laurent1afeecb2014-05-14 08:52:28 -07007544status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007545{
7546 const size_t SIZE = 256;
7547 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007548 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007549
Eric Laurent1afeecb2014-05-14 08:52:28 -07007550 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7551 result.append(buffer);
7552 if (mId != 0) {
7553 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7554 result.append(buffer);
7555 }
7556 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7557 enumToString(sDeviceNameToEnumTable,
7558 ARRAY_SIZE(sDeviceNameToEnumTable),
7559 mDeviceType));
7560 result.append(buffer);
7561 if (mAddress.size() != 0) {
7562 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7563 result.append(buffer);
7564 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007565 write(fd, result.string(), result.size());
7566 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007567
7568 return NO_ERROR;
7569}
7570
Eric Laurent4d416952014-08-10 14:07:09 -07007571status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7572{
7573 const size_t SIZE = 256;
7574 char buffer[SIZE];
7575 String8 result;
7576
7577
7578 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7579 result.append(buffer);
7580 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7581 result.append(buffer);
7582 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7583 result.append(buffer);
7584 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7585 result.append(buffer);
7586 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7587 result.append(buffer);
7588 for (size_t i = 0; i < mPatch.num_sources; i++) {
7589 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7590 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7591 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7592 ARRAY_SIZE(sDeviceNameToEnumTable),
7593 mPatch.sources[i].ext.device.type));
7594 } else {
7595 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7596 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7597 }
7598 result.append(buffer);
7599 }
7600 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7601 result.append(buffer);
7602 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7603 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7604 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7605 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7606 ARRAY_SIZE(sDeviceNameToEnumTable),
7607 mPatch.sinks[i].ext.device.type));
7608 } else {
7609 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7610 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7611 }
7612 result.append(buffer);
7613 }
7614
7615 write(fd, result.string(), result.size());
7616 return NO_ERROR;
7617}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007618
7619// --- audio_policy.conf file parsing
7620
Eric Laurent5dbe4712014-09-19 19:04:57 -07007621uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007622{
7623 uint32_t flag = 0;
7624
7625 // it is OK to cast name to non const here as we are not going to use it after
7626 // strtok() modifies it
7627 char *flagName = strtok(name, "|");
7628 while (flagName != NULL) {
7629 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007630 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7631 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007632 flagName);
7633 }
7634 flagName = strtok(NULL, "|");
7635 }
7636 //force direct flag if offload flag is set: offloading implies a direct output stream
7637 // and all common behaviors are driven by checking only the direct flag
7638 // this should normally be set appropriately in the policy configuration file
7639 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7640 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7641 }
7642
Eric Laurent5dbe4712014-09-19 19:04:57 -07007643 return flag;
7644}
7645
7646uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7647{
7648 uint32_t flag = 0;
7649
7650 // it is OK to cast name to non const here as we are not going to use it after
7651 // strtok() modifies it
7652 char *flagName = strtok(name, "|");
7653 while (flagName != NULL) {
7654 if (strlen(flagName) != 0) {
7655 flag |= stringToEnum(sInputFlagNameToEnumTable,
7656 ARRAY_SIZE(sInputFlagNameToEnumTable),
7657 flagName);
7658 }
7659 flagName = strtok(NULL, "|");
7660 }
7661 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007662}
7663
Eric Laurente0720872014-03-11 09:30:41 -07007664audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007665{
7666 uint32_t device = 0;
7667
7668 char *devName = strtok(name, "|");
7669 while (devName != NULL) {
7670 if (strlen(devName) != 0) {
7671 device |= stringToEnum(sDeviceNameToEnumTable,
7672 ARRAY_SIZE(sDeviceNameToEnumTable),
7673 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007674 }
Eric Laurente552edb2014-03-10 17:42:56 -07007675 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007676 }
Eric Laurente552edb2014-03-10 17:42:56 -07007677 return device;
7678}
7679
Eric Laurente0720872014-03-11 09:30:41 -07007680void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007681{
Eric Laurente552edb2014-03-10 17:42:56 -07007682 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007683 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007684 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007685
Eric Laurent1afeecb2014-05-14 08:52:28 -07007686 node = config_find(root, DEVICES_TAG);
7687 if (node != NULL) {
7688 node = node->first_child;
7689 while (node) {
7690 ALOGV("loadHwModule() loading device %s", node->name);
7691 status_t tmpStatus = module->loadDevice(node);
7692 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7693 status = tmpStatus;
7694 }
7695 node = node->next;
7696 }
7697 }
7698 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007699 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007700 node = node->first_child;
7701 while (node) {
7702 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007703 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007704 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7705 status = tmpStatus;
7706 }
7707 node = node->next;
7708 }
7709 }
7710 node = config_find(root, INPUTS_TAG);
7711 if (node != NULL) {
7712 node = node->first_child;
7713 while (node) {
7714 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007715 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007716 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7717 status = tmpStatus;
7718 }
7719 node = node->next;
7720 }
7721 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007722 loadGlobalConfig(root, module);
7723
Eric Laurente552edb2014-03-10 17:42:56 -07007724 if (status == NO_ERROR) {
7725 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007726 }
7727}
7728
Eric Laurente0720872014-03-11 09:30:41 -07007729void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007730{
7731 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7732 if (node == NULL) {
7733 return;
7734 }
7735
7736 node = node->first_child;
7737 while (node) {
7738 ALOGV("loadHwModules() loading module %s", node->name);
7739 loadHwModule(node);
7740 node = node->next;
7741 }
7742}
7743
Eric Laurent1f2f2232014-06-02 12:01:23 -07007744void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007745{
7746 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007747
Eric Laurente552edb2014-03-10 17:42:56 -07007748 if (node == NULL) {
7749 return;
7750 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007751 DeviceVector declaredDevices;
7752 if (module != NULL) {
7753 declaredDevices = module->mDeclaredDevices;
7754 }
7755
Eric Laurente552edb2014-03-10 17:42:56 -07007756 node = node->first_child;
7757 while (node) {
7758 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007759 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7760 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007761 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7762 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007763 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007764 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007765 ARRAY_SIZE(sDeviceNameToEnumTable),
7766 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007767 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007768 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007769 } else {
7770 ALOGW("loadGlobalConfig() default device not specified");
7771 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007772 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007773 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007774 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7775 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007776 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007777 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7778 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7779 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007780 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7781 uint32_t major, minor;
7782 sscanf((char *)node->value, "%u.%u", &major, &minor);
7783 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7784 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7785 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007786 }
7787 node = node->next;
7788 }
7789}
7790
Eric Laurente0720872014-03-11 09:30:41 -07007791status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007792{
7793 cnode *root;
7794 char *data;
7795
7796 data = (char *)load_file(path, NULL);
7797 if (data == NULL) {
7798 return -ENODEV;
7799 }
7800 root = config_node("", "");
7801 config_load(root, data);
7802
Eric Laurente552edb2014-03-10 17:42:56 -07007803 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007804 // legacy audio_policy.conf files have one global_configuration section
7805 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007806 config_free(root);
7807 free(root);
7808 free(data);
7809
7810 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7811
7812 return NO_ERROR;
7813}
7814
Eric Laurente0720872014-03-11 09:30:41 -07007815void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007816{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007817 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007818 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007819 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7820 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007821 mAvailableOutputDevices.add(mDefaultOutputDevice);
7822 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007823
7824 module = new HwModule("primary");
7825
Eric Laurent1afeecb2014-05-14 08:52:28 -07007826 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007827 profile->mSamplingRates.add(44100);
7828 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7829 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007830 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007831 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7832 module->mOutputProfiles.add(profile);
7833
Eric Laurent1afeecb2014-05-14 08:52:28 -07007834 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007835 profile->mSamplingRates.add(8000);
7836 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7837 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007838 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007839 module->mInputProfiles.add(profile);
7840
7841 mHwModules.add(module);
7842}
7843
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007844audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7845{
7846 // flags to stream type mapping
7847 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7848 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7849 }
7850 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7851 return AUDIO_STREAM_BLUETOOTH_SCO;
7852 }
7853
7854 // usage to stream type mapping
7855 switch (attr->usage) {
7856 case AUDIO_USAGE_MEDIA:
7857 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007858 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7859 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08007860 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08007861 if (isStreamActive(AUDIO_STREAM_ALARM)) {
7862 return AUDIO_STREAM_ALARM;
7863 }
7864 if (isStreamActive(AUDIO_STREAM_RING)) {
7865 return AUDIO_STREAM_RING;
7866 }
7867 if (isInCall()) {
7868 return AUDIO_STREAM_VOICE_CALL;
7869 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08007870 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007871 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7872 return AUDIO_STREAM_SYSTEM;
7873 case AUDIO_USAGE_VOICE_COMMUNICATION:
7874 return AUDIO_STREAM_VOICE_CALL;
7875
7876 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7877 return AUDIO_STREAM_DTMF;
7878
7879 case AUDIO_USAGE_ALARM:
7880 return AUDIO_STREAM_ALARM;
7881 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7882 return AUDIO_STREAM_RING;
7883
7884 case AUDIO_USAGE_NOTIFICATION:
7885 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7886 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7887 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7888 case AUDIO_USAGE_NOTIFICATION_EVENT:
7889 return AUDIO_STREAM_NOTIFICATION;
7890
7891 case AUDIO_USAGE_UNKNOWN:
7892 default:
7893 return AUDIO_STREAM_MUSIC;
7894 }
7895}
Eric Laurente83b55d2014-11-14 10:06:21 -08007896
7897bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
7898 // has flags that map to a strategy?
7899 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7900 return true;
7901 }
7902
7903 // has known usage?
7904 switch (paa->usage) {
7905 case AUDIO_USAGE_UNKNOWN:
7906 case AUDIO_USAGE_MEDIA:
7907 case AUDIO_USAGE_VOICE_COMMUNICATION:
7908 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7909 case AUDIO_USAGE_ALARM:
7910 case AUDIO_USAGE_NOTIFICATION:
7911 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7912 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7913 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7914 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7915 case AUDIO_USAGE_NOTIFICATION_EVENT:
7916 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7917 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7918 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7919 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007920 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08007921 break;
7922 default:
7923 return false;
7924 }
7925 return true;
7926}
7927
Eric Laurente552edb2014-03-10 17:42:56 -07007928}; // namespace android