blob: a58d60cb54a8200c22520259d2ebaa71080312af [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
Hochi Huang327cb702014-09-21 09:47:31 +080029#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX|AUDIO_DEVICE_IN_FM_TUNER)
Eric Laurente552edb2014-03-10 17:42:56 -070030// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -070033// A device mask for all audio input and output devices where matching inputs/outputs on device
34// type alone is not enough: the address must match too
35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36 AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
Eric Laurente552edb2014-03-10 17:42:56 -070037
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070039#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070040
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080046#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070047#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070048#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070049#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070050
Eric Laurent3b73df72014-03-11 09:06:29 -070051namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070052
53// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070054// Definitions for audio_policy.conf file parsing
55// ----------------------------------------------------------------------------
56
57struct StringToEnum {
58 const char *name;
59 uint32_t value;
60};
61
62#define STRING_TO_ENUM(string) { #string, string }
63#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
64
65const StringToEnum sDeviceNameToEnumTable[] = {
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
Jon Eklund11c9fb12014-06-23 14:47:03 -050068 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER_SAFE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070069 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070081 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070087 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
90 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
91 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070092 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050093 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070094 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
98 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -0700101 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700102 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
105 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
106 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700107 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700108 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
110 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
111 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700112 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900113 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700114};
115
Eric Laurent5dbe4712014-09-19 19:04:57 -0700116const StringToEnum sOutputFlagNameToEnumTable[] = {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
122 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
Eric Laurent93c3d412014-08-01 14:48:35 -0700123 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700124};
125
Eric Laurent5dbe4712014-09-19 19:04:57 -0700126const StringToEnum sInputFlagNameToEnumTable[] = {
127 STRING_TO_ENUM(AUDIO_INPUT_FLAG_FAST),
128 STRING_TO_ENUM(AUDIO_INPUT_FLAG_HW_HOTWORD),
129};
130
Eric Laurent3a4311c2014-03-17 12:00:47 -0700131const StringToEnum sFormatNameToEnumTable[] = {
132 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
133 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
134 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
135 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
136 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
137 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
138 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
143 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
144 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
145 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
146 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
147 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
148 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
149 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700150 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700151 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
152 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
153 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
154 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
155 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156};
157
158const StringToEnum sOutChannelsNameToEnumTable[] = {
159 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
160 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700161 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700162 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
163 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
164};
165
166const StringToEnum sInChannelsNameToEnumTable[] = {
167 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
168 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
169 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
170};
171
Eric Laurent1afeecb2014-05-14 08:52:28 -0700172const StringToEnum sGainModeNameToEnumTable[] = {
173 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
174 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
175 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
176};
177
Eric Laurent3a4311c2014-03-17 12:00:47 -0700178
179uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
180 size_t size,
181 const char *name)
182{
183 for (size_t i = 0; i < size; i++) {
184 if (strcmp(table[i].name, name) == 0) {
185 ALOGV("stringToEnum() found %s", table[i].name);
186 return table[i].value;
187 }
188 }
189 return 0;
190}
191
192const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
193 size_t size,
194 uint32_t value)
195{
196 for (size_t i = 0; i < size; i++) {
197 if (table[i].value == value) {
198 return table[i].name;
199 }
200 }
201 return "";
202}
203
204bool AudioPolicyManager::stringToBool(const char *value)
205{
206 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
207}
208
209
210// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700211// AudioPolicyInterface implementation
212// ----------------------------------------------------------------------------
213
Eric Laurente0720872014-03-11 09:30:41 -0700214status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700215 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700216 const char *device_address)
217{
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800218 return setDeviceConnectionStateInt(device, state, device_address);
219}
220
221status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800222 audio_policy_dev_state_t state,
223 const char *device_address)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800224{
Eric Laurent22226012014-08-01 17:00:54 -0700225 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
Eric Laurenta1d525f2015-01-29 13:36:45 -0800226 device, state, device_address != NULL ? device_address : "");
Eric Laurente552edb2014-03-10 17:42:56 -0700227
228 // connect/disconnect only 1 device at a time
229 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
230
Eric Laurenta1d525f2015-01-29 13:36:45 -0800231 sp<DeviceDescriptor> devDesc = getDeviceDescriptor(device, device_address);
232
Eric Laurente552edb2014-03-10 17:42:56 -0700233 // handle output devices
234 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700235 SortedVector <audio_io_handle_t> outputs;
236
Eric Laurent3a4311c2014-03-17 12:00:47 -0700237 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
238
Eric Laurente552edb2014-03-10 17:42:56 -0700239 // save a copy of the opened output descriptors before any output is opened or closed
240 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
241 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700242 switch (state)
243 {
244 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700245 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700246 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700247 ALOGW("setDeviceConnectionState() device already connected: %x", device);
248 return INVALID_OPERATION;
249 }
250 ALOGV("setDeviceConnectionState() connecting device %x", device);
251
Eric Laurente552edb2014-03-10 17:42:56 -0700252 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700253 index = mAvailableOutputDevices.add(devDesc);
254 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700255 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700256 if (module == 0) {
257 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
258 device);
259 mAvailableOutputDevices.remove(devDesc);
260 return INVALID_OPERATION;
261 }
262 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700263 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700264 } else {
265 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700266 }
267
Eric Laurenta1d525f2015-01-29 13:36:45 -0800268 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700269 mAvailableOutputDevices.remove(devDesc);
270 return INVALID_OPERATION;
271 }
272 // outputs should never be empty here
273 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
274 "checkOutputsForDevice() returned no outputs but status OK");
275 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
276 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700277 break;
278 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700279 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700280 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700281 ALOGW("setDeviceConnectionState() device not connected: %x", device);
282 return INVALID_OPERATION;
283 }
284
Paul McLean5c477aa2014-08-20 16:47:57 -0700285 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
286
287 // Set Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800288 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700289 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
290 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
291
Eric Laurente552edb2014-03-10 17:42:56 -0700292 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700293 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700294
Eric Laurenta1d525f2015-01-29 13:36:45 -0800295 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
Eric Laurente552edb2014-03-10 17:42:56 -0700296 } break;
297
298 default:
299 ALOGE("setDeviceConnectionState() invalid state: %x", state);
300 return BAD_VALUE;
301 }
302
Eric Laurent3a4311c2014-03-17 12:00:47 -0700303 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
304 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700305 checkA2dpSuspend();
306 checkOutputForAllStrategies();
307 // outputs must be closed after checkOutputForAllStrategies() is executed
308 if (!outputs.isEmpty()) {
309 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700310 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700311 // close unused outputs after device disconnection or direct outputs that have been
312 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700313 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700314 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
315 (desc->mDirectOpenCount == 0))) {
316 closeOutput(outputs[i]);
317 }
318 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700319 // check again after closing A2DP output to reset mA2dpSuspended if needed
320 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700321 }
322
323 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 if (mPhoneState == AUDIO_MODE_IN_CALL) {
325 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
326 updateCallRouting(newDevice);
327 }
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700329 audio_io_handle_t output = mOutputs.keyAt(i);
330 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
331 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
332 true /*fromCache*/);
333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
336 bool force = !mOutputs.valueAt(i)->isDuplicated()
337 && (!deviceDistinguishesOnAddress(device)
338 // always force when disconnecting (a non-duplicated device)
339 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
340 setOutputDevice(output, newDevice, force, 0);
341 }
Eric Laurente552edb2014-03-10 17:42:56 -0700342 }
343
Eric Laurent72aa32f2014-05-30 18:51:48 -0700344 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700345 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700346 } // end if is output device
347
Eric Laurente552edb2014-03-10 17:42:56 -0700348 // handle input devices
349 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700350 SortedVector <audio_io_handle_t> inputs;
351
Eric Laurent3a4311c2014-03-17 12:00:47 -0700352 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700353 switch (state)
354 {
355 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700356 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700357 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700358 ALOGW("setDeviceConnectionState() device already connected: %d", device);
359 return INVALID_OPERATION;
360 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700361 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700362 if (module == NULL) {
363 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
364 device);
365 return INVALID_OPERATION;
366 }
Eric Laurenta1d525f2015-01-29 13:36:45 -0800367 if (checkInputsForDevice(device, state, inputs, devDesc->mAddress) != NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -0700368 return INVALID_OPERATION;
369 }
370
Eric Laurent3a4311c2014-03-17 12:00:47 -0700371 index = mAvailableInputDevices.add(devDesc);
372 if (index >= 0) {
373 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700374 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700375 } else {
376 return NO_MEMORY;
377 }
Eric Laurentd4692962014-05-05 18:13:44 -0700378 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700379
380 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700381 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700382 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700383 ALOGW("setDeviceConnectionState() device not connected: %d", device);
384 return INVALID_OPERATION;
385 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700386
387 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
388
389 // Set Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800390 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700391 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
392 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
393
Eric Laurenta1d525f2015-01-29 13:36:45 -0800394 checkInputsForDevice(device, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700395 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700396
Eric Laurentd4692962014-05-05 18:13:44 -0700397 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700398
399 default:
400 ALOGE("setDeviceConnectionState() invalid state: %x", state);
401 return BAD_VALUE;
402 }
403
Eric Laurentd4692962014-05-05 18:13:44 -0700404 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700405
Eric Laurentc2730ba2014-07-20 15:47:07 -0700406 if (mPhoneState == AUDIO_MODE_IN_CALL) {
407 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
408 updateCallRouting(newDevice);
409 }
410
Eric Laurentb52c1522014-05-20 11:27:36 -0700411 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700412 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700413 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700414
415 ALOGW("setDeviceConnectionState() invalid device: %x", device);
416 return BAD_VALUE;
417}
418
Eric Laurente0720872014-03-11 09:30:41 -0700419audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700420 const char *device_address)
421{
Eric Laurenta1d525f2015-01-29 13:36:45 -0800422 sp<DeviceDescriptor> devDesc = getDeviceDescriptor(device, device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700423 DeviceVector *deviceVector;
424
Eric Laurente552edb2014-03-10 17:42:56 -0700425 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700426 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700427 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700428 deviceVector = &mAvailableInputDevices;
429 } else {
430 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
431 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700432 }
433
Eric Laurenta1d525f2015-01-29 13:36:45 -0800434 ssize_t index = deviceVector->indexOf(devDesc);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700435 if (index >= 0) {
436 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
437 } else {
438 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
439 }
Eric Laurente552edb2014-03-10 17:42:56 -0700440}
441
Eric Laurenta1d525f2015-01-29 13:36:45 -0800442sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::getDeviceDescriptor(
443 const audio_devices_t device,
444 const char *device_address)
445{
446 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
447 // handle legacy remote submix case where the address was not always specified
448 if (deviceDistinguishesOnAddress(device) && (address.length() == 0)) {
449 address = String8("0");
450 }
451
452 for (size_t i = 0; i < mHwModules.size(); i++) {
453 if (mHwModules[i]->mHandle == 0) {
454 continue;
455 }
456 DeviceVector deviceList =
457 mHwModules[i]->mDeclaredDevices.getDevicesFromTypeAddr(device, address);
458 if (!deviceList.isEmpty()) {
459 return deviceList.itemAt(0);
460 }
461 deviceList = mHwModules[i]->mDeclaredDevices.getDevicesFromType(device);
462 if (!deviceList.isEmpty()) {
463 return deviceList.itemAt(0);
464 }
465 }
466
467 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
468 devDesc->mAddress = address;
469 return devDesc;
470}
471
Eric Laurentc2730ba2014-07-20 15:47:07 -0700472void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
473{
474 bool createTxPatch = false;
475 struct audio_patch patch;
476 patch.num_sources = 1;
477 patch.num_sinks = 1;
478 status_t status;
479 audio_patch_handle_t afPatchHandle;
480 DeviceVector deviceList;
481
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800482 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700483 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
484
485 // release existing RX patch if any
486 if (mCallRxPatch != 0) {
487 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
488 mCallRxPatch.clear();
489 }
490 // release TX patch if any
491 if (mCallTxPatch != 0) {
492 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
493 mCallTxPatch.clear();
494 }
495
496 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
497 // via setOutputDevice() on primary output.
498 // Otherwise, create two audio patches for TX and RX path.
499 if (availablePrimaryOutputDevices() & rxDevice) {
500 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
501 // If the TX device is also on the primary HW module, setOutputDevice() will take care
502 // of it due to legacy implementation. If not, create a patch.
503 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
504 == AUDIO_DEVICE_NONE) {
505 createTxPatch = true;
506 }
507 } else {
508 // create RX path audio patch
509 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
510 ALOG_ASSERT(!deviceList.isEmpty(),
511 "updateCallRouting() selected device not in output device list");
512 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
513 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
514 ALOG_ASSERT(!deviceList.isEmpty(),
515 "updateCallRouting() no telephony RX device");
516 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
517
518 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
519 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
520
521 // request to reuse existing output stream if one is already opened to reach the RX device
522 SortedVector<audio_io_handle_t> outputs =
523 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700524 audio_io_handle_t output = selectOutput(outputs,
525 AUDIO_OUTPUT_FLAG_NONE,
526 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700527 if (output != AUDIO_IO_HANDLE_NONE) {
528 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
529 ALOG_ASSERT(!outputDesc->isDuplicated(),
530 "updateCallRouting() RX device output is duplicated");
531 outputDesc->toAudioPortConfig(&patch.sources[1]);
532 patch.num_sources = 2;
533 }
534
535 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
536 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
537 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
538 status);
539 if (status == NO_ERROR) {
540 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
541 &patch, mUidCached);
542 mCallRxPatch->mAfPatchHandle = afPatchHandle;
543 mCallRxPatch->mUid = mUidCached;
544 }
545 createTxPatch = true;
546 }
547 if (createTxPatch) {
548
549 struct audio_patch patch;
550 patch.num_sources = 1;
551 patch.num_sinks = 1;
552 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
553 ALOG_ASSERT(!deviceList.isEmpty(),
554 "updateCallRouting() selected device not in input device list");
555 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
556 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
557 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
558 ALOG_ASSERT(!deviceList.isEmpty(),
559 "updateCallRouting() no telephony TX device");
560 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
561 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
562
563 SortedVector<audio_io_handle_t> outputs =
564 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700565 audio_io_handle_t output = selectOutput(outputs,
566 AUDIO_OUTPUT_FLAG_NONE,
567 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700568 // request to reuse existing output stream if one is already opened to reach the TX
569 // path output device
570 if (output != AUDIO_IO_HANDLE_NONE) {
571 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
572 ALOG_ASSERT(!outputDesc->isDuplicated(),
573 "updateCallRouting() RX device output is duplicated");
574 outputDesc->toAudioPortConfig(&patch.sources[1]);
575 patch.num_sources = 2;
576 }
577
578 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
579 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
580 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
581 status);
582 if (status == NO_ERROR) {
583 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
584 &patch, mUidCached);
585 mCallTxPatch->mAfPatchHandle = afPatchHandle;
586 mCallTxPatch->mUid = mUidCached;
587 }
588 }
589}
590
Eric Laurente0720872014-03-11 09:30:41 -0700591void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700592{
593 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700594 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700595 ALOGW("setPhoneState() invalid state %d", state);
596 return;
597 }
598
599 if (state == mPhoneState ) {
600 ALOGW("setPhoneState() setting same state %d", state);
601 return;
602 }
603
604 // if leaving call state, handle special case of active streams
605 // pertaining to sonification strategy see handleIncallSonification()
606 if (isInCall()) {
607 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700608 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800609 if (stream == AUDIO_STREAM_PATCH) {
610 continue;
611 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700612 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700613 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800614
615 // force reevaluating accessibility routing when call starts
616 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700617 }
618
619 // store previous phone state for management of sonification strategy below
620 int oldState = mPhoneState;
621 mPhoneState = state;
622 bool force = false;
623
624 // are we entering or starting a call
625 if (!isStateInCall(oldState) && isStateInCall(state)) {
626 ALOGV(" Entering call in setPhoneState()");
627 // force routing command to audio hardware when starting a call
628 // even if no device change is needed
629 force = true;
630 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
631 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
632 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
633 }
634 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
635 ALOGV(" Exiting call in setPhoneState()");
636 // force routing command to audio hardware when exiting a call
637 // even if no device change is needed
638 force = true;
639 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
640 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
641 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
642 }
643 } else if (isStateInCall(state) && (state != oldState)) {
644 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
645 // force routing command to audio hardware when switching between telephony and VoIP
646 // even if no device change is needed
647 force = true;
648 }
649
650 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700651 checkA2dpSuspend();
652 checkOutputForAllStrategies();
653 updateDevicesAndOutputs();
654
Eric Laurent1f2f2232014-06-02 12:01:23 -0700655 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700656
Eric Laurente552edb2014-03-10 17:42:56 -0700657 int delayMs = 0;
658 if (isStateInCall(state)) {
659 nsecs_t sysTime = systemTime();
660 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700661 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700662 // mute media and sonification strategies and delay device switch by the largest
663 // latency of any output where either strategy is active.
664 // This avoid sending the ring tone or music tail into the earpiece or headset.
665 if ((desc->isStrategyActive(STRATEGY_MEDIA,
666 SONIFICATION_HEADSET_MUSIC_DELAY,
667 sysTime) ||
668 desc->isStrategyActive(STRATEGY_SONIFICATION,
669 SONIFICATION_HEADSET_MUSIC_DELAY,
670 sysTime)) &&
671 (delayMs < (int)desc->mLatency*2)) {
672 delayMs = desc->mLatency*2;
673 }
674 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
675 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
676 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
677 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
678 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
679 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
680 }
681 }
682
Eric Laurentc2730ba2014-07-20 15:47:07 -0700683 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
684 // the device returned is not necessarily reachable via this output
685 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
686 // force routing command to audio hardware when ending call
687 // even if no device change is needed
688 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
689 rxDevice = hwOutputDesc->device();
690 }
Eric Laurente552edb2014-03-10 17:42:56 -0700691
Eric Laurentc2730ba2014-07-20 15:47:07 -0700692 if (state == AUDIO_MODE_IN_CALL) {
693 updateCallRouting(rxDevice, delayMs);
694 } else if (oldState == AUDIO_MODE_IN_CALL) {
695 if (mCallRxPatch != 0) {
696 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
697 mCallRxPatch.clear();
698 }
699 if (mCallTxPatch != 0) {
700 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
701 mCallTxPatch.clear();
702 }
703 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
704 } else {
705 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
706 }
Eric Laurente552edb2014-03-10 17:42:56 -0700707 // if entering in call state, handle special case of active streams
708 // pertaining to sonification strategy see handleIncallSonification()
709 if (isStateInCall(state)) {
710 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700711 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800712 if (stream == AUDIO_STREAM_PATCH) {
713 continue;
714 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700715 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700716 }
717 }
718
719 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700720 if (state == AUDIO_MODE_RINGTONE &&
721 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700722 mLimitRingtoneVolume = true;
723 } else {
724 mLimitRingtoneVolume = false;
725 }
726}
727
Eric Laurente0720872014-03-11 09:30:41 -0700728void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700729 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700730{
731 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
732
733 bool forceVolumeReeval = false;
734 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700735 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
736 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
737 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700738 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
739 return;
740 }
741 forceVolumeReeval = true;
742 mForceUse[usage] = config;
743 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700744 case AUDIO_POLICY_FORCE_FOR_MEDIA:
745 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
746 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
747 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
748 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Hochi Huang327cb702014-09-21 09:47:31 +0800749 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
Eric Laurente552edb2014-03-10 17:42:56 -0700750 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
751 return;
752 }
753 mForceUse[usage] = config;
754 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700755 case AUDIO_POLICY_FORCE_FOR_RECORD:
756 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
757 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700758 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
759 return;
760 }
761 mForceUse[usage] = config;
762 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700763 case AUDIO_POLICY_FORCE_FOR_DOCK:
764 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
765 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
766 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
767 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
768 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700769 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
770 }
771 forceVolumeReeval = true;
772 mForceUse[usage] = config;
773 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700774 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
775 if (config != AUDIO_POLICY_FORCE_NONE &&
776 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700777 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
778 }
779 forceVolumeReeval = true;
780 mForceUse[usage] = config;
781 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900782 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
783 if (config != AUDIO_POLICY_FORCE_NONE &&
784 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
785 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
786 }
787 mForceUse[usage] = config;
788 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700789 default:
790 ALOGW("setForceUse() invalid usage %d", usage);
791 break;
792 }
793
794 // check for device and output changes triggered by new force usage
795 checkA2dpSuspend();
796 checkOutputForAllStrategies();
797 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700798 if (mPhoneState == AUDIO_MODE_IN_CALL) {
799 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
800 updateCallRouting(newDevice);
801 }
Eric Laurente552edb2014-03-10 17:42:56 -0700802 for (size_t i = 0; i < mOutputs.size(); i++) {
803 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700804 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700805 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
806 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
807 }
Eric Laurente552edb2014-03-10 17:42:56 -0700808 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
809 applyStreamVolumes(output, newDevice, 0, true);
810 }
811 }
812
813 audio_io_handle_t activeInput = getActiveInput();
814 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700815 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700816 }
817
818}
819
Eric Laurente0720872014-03-11 09:30:41 -0700820audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700821{
822 return mForceUse[usage];
823}
824
Eric Laurente0720872014-03-11 09:30:41 -0700825void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700826{
827 ALOGV("setSystemProperty() property %s, value %s", property, value);
828}
829
830// Find a direct output profile compatible with the parameters passed, even if the input flags do
831// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700832sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700833 audio_devices_t device,
834 uint32_t samplingRate,
835 audio_format_t format,
836 audio_channel_mask_t channelMask,
837 audio_output_flags_t flags)
838{
839 for (size_t i = 0; i < mHwModules.size(); i++) {
840 if (mHwModules[i]->mHandle == 0) {
841 continue;
842 }
843 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700844 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent275e8e92014-11-30 15:14:47 -0800845 bool found = profile->isCompatibleProfile(device, String8(""), samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -0700846 NULL /*updatedSamplingRate*/, format, channelMask,
847 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
848 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700849 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
850 return profile;
851 }
Eric Laurente552edb2014-03-10 17:42:56 -0700852 }
853 }
854 return 0;
855}
856
Eric Laurente0720872014-03-11 09:30:41 -0700857audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700858 uint32_t samplingRate,
859 audio_format_t format,
860 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700861 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700862 const audio_offload_info_t *offloadInfo)
863{
Eric Laurent3b73df72014-03-11 09:06:29 -0700864 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700865 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
866 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
867 device, stream, samplingRate, format, channelMask, flags);
868
Eric Laurente83b55d2014-11-14 10:06:21 -0800869 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
870 stream, samplingRate,format, channelMask,
871 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700872}
873
Eric Laurente83b55d2014-11-14 10:06:21 -0800874status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
875 audio_io_handle_t *output,
876 audio_session_t session,
877 audio_stream_type_t *stream,
878 uint32_t samplingRate,
879 audio_format_t format,
880 audio_channel_mask_t channelMask,
881 audio_output_flags_t flags,
882 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700883{
Eric Laurente83b55d2014-11-14 10:06:21 -0800884 audio_attributes_t attributes;
885 if (attr != NULL) {
886 if (!isValidAttributes(attr)) {
887 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
888 attr->usage, attr->content_type, attr->flags,
889 attr->tags);
890 return BAD_VALUE;
891 }
892 attributes = *attr;
893 } else {
894 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
895 ALOGE("getOutputForAttr(): invalid stream type");
896 return BAD_VALUE;
897 }
898 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700899 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800900
Eric Laurent275e8e92014-11-30 15:14:47 -0800901 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
902 sp<AudioOutputDescriptor> desc;
903 if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_PLAYERS) {
904 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
905 if ((RULE_MATCH_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
906 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage == attributes.usage) ||
907 (RULE_EXCLUDE_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
908 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage != attributes.usage)) {
909 desc = mPolicyMixes[i]->mOutput;
910 break;
911 }
912 if (strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
913 strncmp(attributes.tags + strlen("addr="),
914 mPolicyMixes[i]->mMix.mRegistrationId.string(),
915 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
916 desc = mPolicyMixes[i]->mOutput;
917 break;
918 }
919 }
920 } else if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_RECORDERS) {
921 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE &&
922 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
923 strncmp(attributes.tags + strlen("addr="),
924 mPolicyMixes[i]->mMix.mRegistrationId.string(),
925 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
926 desc = mPolicyMixes[i]->mOutput;
Eric Laurent275e8e92014-11-30 15:14:47 -0800927 }
928 }
929 if (desc != 0) {
930 if (!audio_is_linear_pcm(format)) {
931 return BAD_VALUE;
932 }
Eric Laurentc722f302014-12-10 11:21:49 -0800933 desc->mPolicyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -0800934 *stream = streamTypefromAttributesInt(&attributes);
935 *output = desc->mIoHandle;
936 ALOGV("getOutputForAttr() returns output %d", *output);
937 return NO_ERROR;
938 }
939 }
940 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
941 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
942 return BAD_VALUE;
943 }
944
Eric Laurent93c3d412014-08-01 14:48:35 -0700945 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800946 attributes.usage, attributes.content_type, attributes.tags, attributes.flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700947
Eric Laurente83b55d2014-11-14 10:06:21 -0800948 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700949 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700950
Eric Laurente83b55d2014-11-14 10:06:21 -0800951 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700952 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
953 }
954
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700955 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700956 device, samplingRate, format, channelMask, flags);
957
Eric Laurente83b55d2014-11-14 10:06:21 -0800958 *stream = streamTypefromAttributesInt(&attributes);
959 *output = getOutputForDevice(device, session, *stream,
960 samplingRate, format, channelMask,
961 flags, offloadInfo);
962 if (*output == AUDIO_IO_HANDLE_NONE) {
963 return INVALID_OPERATION;
964 }
965 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700966}
967
968audio_io_handle_t AudioPolicyManager::getOutputForDevice(
969 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800970 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700971 audio_stream_type_t stream,
972 uint32_t samplingRate,
973 audio_format_t format,
974 audio_channel_mask_t channelMask,
975 audio_output_flags_t flags,
976 const audio_offload_info_t *offloadInfo)
977{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700978 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700979 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700980 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700981
Eric Laurente552edb2014-03-10 17:42:56 -0700982#ifdef AUDIO_POLICY_TEST
983 if (mCurOutput != 0) {
984 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
985 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
986
987 if (mTestOutputs[mCurOutput] == 0) {
988 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700989 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700990 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700991 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700992 outputDesc->mFlags =
993 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700994 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700995 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
996 config.sample_rate = mTestSamplingRate;
997 config.channel_mask = mTestChannels;
998 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700999 if (offloadInfo != NULL) {
1000 config.offload_info = *offloadInfo;
1001 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001002 status = mpClientInterface->openOutput(0,
1003 &mTestOutputs[mCurOutput],
1004 &config,
1005 &outputDesc->mDevice,
1006 String8(""),
1007 &outputDesc->mLatency,
1008 outputDesc->mFlags);
1009 if (status == NO_ERROR) {
1010 outputDesc->mSamplingRate = config.sample_rate;
1011 outputDesc->mFormat = config.format;
1012 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -07001013 AudioParameter outputCmd = AudioParameter();
1014 outputCmd.addInt(String8("set_id"),mCurOutput);
1015 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
1016 addOutput(mTestOutputs[mCurOutput], outputDesc);
1017 }
1018 }
1019 return mTestOutputs[mCurOutput];
1020 }
1021#endif //AUDIO_POLICY_TEST
1022
1023 // open a direct output if required by specified parameters
1024 //force direct flag if offload flag is set: offloading implies a direct output stream
1025 // and all common behaviors are driven by checking only the direct flag
1026 // this should normally be set appropriately in the policy configuration file
1027 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07001028 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001029 }
Eric Laurent93c3d412014-08-01 14:48:35 -07001030 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1031 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
1032 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001033 // only allow deep buffering for music stream type
1034 if (stream != AUDIO_STREAM_MUSIC) {
1035 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1036 }
Eric Laurente552edb2014-03-10 17:42:56 -07001037
Eric Laurentb732cf52014-09-24 19:08:21 -07001038 sp<IOProfile> profile;
1039
1040 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001041 // and not explicitly requested
1042 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1043 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -07001044 audio_channel_count_from_out_mask(channelMask) <= 2) {
1045 goto non_direct_output;
1046 }
1047
Eric Laurente552edb2014-03-10 17:42:56 -07001048 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1049 // creating an offloaded track and tearing it down immediately after start when audioflinger
1050 // detects there is an active non offloadable effect.
1051 // FIXME: We should check the audio session here but we do not have it in this context.
1052 // This may prevent offloading in rare situations where effects are left active by apps
1053 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001054
Eric Laurente552edb2014-03-10 17:42:56 -07001055 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1056 !isNonOffloadableEffectEnabled()) {
1057 profile = getProfileForDirectOutput(device,
1058 samplingRate,
1059 format,
1060 channelMask,
1061 (audio_output_flags_t)flags);
1062 }
1063
Eric Laurent1c333e22014-05-20 10:48:17 -07001064 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001065 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -07001066
1067 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001068 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001069 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1070 outputDesc = desc;
1071 // reuse direct output if currently open and configured with same parameters
1072 if ((samplingRate == outputDesc->mSamplingRate) &&
1073 (format == outputDesc->mFormat) &&
1074 (channelMask == outputDesc->mChannelMask)) {
1075 outputDesc->mDirectOpenCount++;
1076 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
1077 return mOutputs.keyAt(i);
1078 }
1079 }
1080 }
1081 // close direct output if currently open and configured with different parameters
1082 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001083 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001084 }
1085 outputDesc = new AudioOutputDescriptor(profile);
1086 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001087 outputDesc->mLatency = 0;
1088 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001089 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1090 config.sample_rate = samplingRate;
1091 config.channel_mask = channelMask;
1092 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001093 if (offloadInfo != NULL) {
1094 config.offload_info = *offloadInfo;
1095 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001096 status = mpClientInterface->openOutput(profile->mModule->mHandle,
1097 &output,
1098 &config,
1099 &outputDesc->mDevice,
1100 String8(""),
1101 &outputDesc->mLatency,
1102 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001103
1104 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001105 if (status != NO_ERROR ||
1106 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1107 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1108 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001109 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1110 "format %d %d, channelMask %04x %04x", output, samplingRate,
1111 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1112 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001113 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001114 mpClientInterface->closeOutput(output);
1115 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001116 // fall back to mixer output if possible when the direct output could not be open
1117 if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE) {
1118 goto non_direct_output;
1119 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001120 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001121 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001122 outputDesc->mSamplingRate = config.sample_rate;
1123 outputDesc->mChannelMask = config.channel_mask;
1124 outputDesc->mFormat = config.format;
1125 outputDesc->mRefCount[stream] = 0;
1126 outputDesc->mStopTime[stream] = 0;
1127 outputDesc->mDirectOpenCount = 1;
1128
Eric Laurente552edb2014-03-10 17:42:56 -07001129 audio_io_handle_t srcOutput = getOutputForEffect();
1130 addOutput(output, outputDesc);
1131 audio_io_handle_t dstOutput = getOutputForEffect();
1132 if (dstOutput == output) {
1133 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1134 }
1135 mPreviousOutputs = mOutputs;
1136 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001137 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001138 return output;
1139 }
1140
Eric Laurentb732cf52014-09-24 19:08:21 -07001141non_direct_output:
1142
Eric Laurente552edb2014-03-10 17:42:56 -07001143 // ignoring channel mask due to downmix capability in mixer
1144
1145 // open a non direct output
1146
1147 // for non direct outputs, only PCM is supported
1148 if (audio_is_linear_pcm(format)) {
1149 // get which output is suitable for the specified stream. The actual
1150 // routing change will happen when startOutput() will be called
1151 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1152
Eric Laurent8838a382014-09-08 16:44:28 -07001153 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1154 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1155 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001156 }
1157 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1158 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1159
1160 ALOGV("getOutput() returns output %d", output);
1161
1162 return output;
1163}
1164
Eric Laurente0720872014-03-11 09:30:41 -07001165audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001166 audio_output_flags_t flags,
1167 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001168{
1169 // select one output among several that provide a path to a particular device or set of
1170 // devices (the list was previously build by getOutputsForDevice()).
1171 // The priority is as follows:
1172 // 1: the output with the highest number of requested policy flags
1173 // 2: the primary output
1174 // 3: the first output in the list
1175
1176 if (outputs.size() == 0) {
1177 return 0;
1178 }
1179 if (outputs.size() == 1) {
1180 return outputs[0];
1181 }
1182
1183 int maxCommonFlags = 0;
1184 audio_io_handle_t outputFlags = 0;
1185 audio_io_handle_t outputPrimary = 0;
1186
1187 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001188 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001189 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001190 // if a valid format is specified, skip output if not compatible
1191 if (format != AUDIO_FORMAT_INVALID) {
1192 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1193 if (format != outputDesc->mFormat) {
1194 continue;
1195 }
1196 } else if (!audio_is_linear_pcm(format)) {
1197 continue;
1198 }
1199 }
1200
Eric Laurent3b73df72014-03-11 09:06:29 -07001201 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001202 if (commonFlags > maxCommonFlags) {
1203 outputFlags = outputs[i];
1204 maxCommonFlags = commonFlags;
1205 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1206 }
1207 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1208 outputPrimary = outputs[i];
1209 }
1210 }
1211 }
1212
1213 if (outputFlags != 0) {
1214 return outputFlags;
1215 }
1216 if (outputPrimary != 0) {
1217 return outputPrimary;
1218 }
1219
1220 return outputs[0];
1221}
1222
Eric Laurente0720872014-03-11 09:30:41 -07001223status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001224 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001225 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001226{
1227 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1228 ssize_t index = mOutputs.indexOfKey(output);
1229 if (index < 0) {
1230 ALOGW("startOutput() unknown output %d", output);
1231 return BAD_VALUE;
1232 }
1233
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001234 // cannot start playback of STREAM_TTS if any other output is being used
1235 uint32_t beaconMuteLatency = 0;
1236 if (stream == AUDIO_STREAM_TTS) {
1237 ALOGV("\t found BEACON stream");
1238 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1239 return INVALID_OPERATION;
1240 } else {
1241 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1242 }
1243 } else {
1244 // some playback other than beacon starts
1245 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1246 }
1247
Eric Laurent1f2f2232014-06-02 12:01:23 -07001248 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001249
1250 // increment usage count for this stream on the requested output:
1251 // NOTE that the usage count is the same for duplicated output and hardware output which is
1252 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1253 outputDesc->changeRefCount(stream, 1);
1254
1255 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001256 // starting an output being rerouted?
1257 audio_devices_t newDevice;
Eric Laurentc722f302014-12-10 11:21:49 -08001258 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001259 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1260 } else {
1261 newDevice = getNewOutputDevice(output, false /*fromCache*/);
1262 }
Eric Laurente552edb2014-03-10 17:42:56 -07001263 routing_strategy strategy = getStrategy(stream);
1264 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001265 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1266 (beaconMuteLatency > 0);
1267 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001268 bool force = false;
1269 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001270 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001271 if (desc != outputDesc) {
1272 // force a device change if any other output is managed by the same hw
1273 // module and has a current device selection that differs from selected device.
1274 // In this case, the audio HAL must receive the new device selection so that it can
1275 // change the device currently selected by the other active output.
1276 if (outputDesc->sharesHwModuleWith(desc) &&
1277 desc->device() != newDevice) {
1278 force = true;
1279 }
1280 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001281 // a notification so that audio focus effect can propagate, or that a mute/unmute
1282 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001283 uint32_t latency = desc->latency();
1284 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1285 waitMs = latency;
1286 }
1287 }
1288 }
1289 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1290
1291 // handle special case for sonification while in call
1292 if (isInCall()) {
1293 handleIncallSonification(stream, true, false);
1294 }
1295
1296 // apply volume rules for current stream and device if necessary
1297 checkAndSetVolume(stream,
1298 mStreams[stream].getVolumeIndex(newDevice),
1299 output,
1300 newDevice);
1301
1302 // update the outputs if starting an output with a stream that can affect notification
1303 // routing
1304 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001305
1306 // Automatically enable the remote submix input when output is started on a re routing mix
1307 // of type MIX_TYPE_RECORDERS
1308 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1309 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001310 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001311 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1312 outputDesc->mPolicyMix->mRegistrationId);
1313 }
1314
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001315 // force reevaluating accessibility routing when ringtone or alarm starts
1316 if (strategy == STRATEGY_SONIFICATION) {
1317 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1318 }
1319
Eric Laurente552edb2014-03-10 17:42:56 -07001320 if (waitMs > muteWaitMs) {
1321 usleep((waitMs - muteWaitMs) * 2 * 1000);
1322 }
1323 }
1324 return NO_ERROR;
1325}
1326
1327
Eric Laurente0720872014-03-11 09:30:41 -07001328status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001329 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001330 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001331{
1332 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1333 ssize_t index = mOutputs.indexOfKey(output);
1334 if (index < 0) {
1335 ALOGW("stopOutput() unknown output %d", output);
1336 return BAD_VALUE;
1337 }
1338
Eric Laurent1f2f2232014-06-02 12:01:23 -07001339 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001340
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001341 // always handle stream stop, check which stream type is stopping
1342 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1343
Eric Laurente552edb2014-03-10 17:42:56 -07001344 // handle special case for sonification while in call
1345 if (isInCall()) {
1346 handleIncallSonification(stream, false, false);
1347 }
1348
1349 if (outputDesc->mRefCount[stream] > 0) {
1350 // decrement usage count of this stream on the output
1351 outputDesc->changeRefCount(stream, -1);
1352 // store time at which the stream was stopped - see isStreamActive()
1353 if (outputDesc->mRefCount[stream] == 0) {
Eric Laurentc722f302014-12-10 11:21:49 -08001354 // Automatically disable the remote submix input when output is stopped on a
1355 // re routing mix of type MIX_TYPE_RECORDERS
1356 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1357 outputDesc->mPolicyMix != NULL &&
1358 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001359 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001360 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1361 outputDesc->mPolicyMix->mRegistrationId);
1362 }
1363
Eric Laurente552edb2014-03-10 17:42:56 -07001364 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001365 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001366 // delay the device switch by twice the latency because stopOutput() is executed when
1367 // the track stop() command is received and at that time the audio track buffer can
1368 // still contain data that needs to be drained. The latency only covers the audio HAL
1369 // and kernel buffers. Also the latency does not always include additional delay in the
1370 // audio path (audio DSP, CODEC ...)
1371 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1372
1373 // force restoring the device selection on other active outputs if it differs from the
1374 // one being selected for this output
1375 for (size_t i = 0; i < mOutputs.size(); i++) {
1376 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001377 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001378 if (curOutput != output &&
1379 desc->isActive() &&
1380 outputDesc->sharesHwModuleWith(desc) &&
1381 (newDevice != desc->device())) {
1382 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001383 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001384 true,
1385 outputDesc->mLatency*2);
1386 }
1387 }
1388 // update the outputs if stopping one with a stream that can affect notification routing
1389 handleNotificationRoutingForStream(stream);
1390 }
1391 return NO_ERROR;
1392 } else {
1393 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1394 return INVALID_OPERATION;
1395 }
1396}
1397
Eric Laurente83b55d2014-11-14 10:06:21 -08001398void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001399 audio_stream_type_t stream __unused,
1400 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001401{
1402 ALOGV("releaseOutput() %d", output);
1403 ssize_t index = mOutputs.indexOfKey(output);
1404 if (index < 0) {
1405 ALOGW("releaseOutput() releasing unknown output %d", output);
1406 return;
1407 }
1408
1409#ifdef AUDIO_POLICY_TEST
1410 int testIndex = testOutputIndex(output);
1411 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001412 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001413 if (outputDesc->isActive()) {
1414 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001415 mOutputs.removeItem(output);
1416 mTestOutputs[testIndex] = 0;
1417 }
1418 return;
1419 }
1420#endif //AUDIO_POLICY_TEST
1421
Eric Laurent1f2f2232014-06-02 12:01:23 -07001422 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001423 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001424 if (desc->mDirectOpenCount <= 0) {
1425 ALOGW("releaseOutput() invalid open count %d for output %d",
1426 desc->mDirectOpenCount, output);
1427 return;
1428 }
1429 if (--desc->mDirectOpenCount == 0) {
1430 closeOutput(output);
1431 // If effects where present on the output, audioflinger moved them to the primary
1432 // output by default: move them back to the appropriate output.
1433 audio_io_handle_t dstOutput = getOutputForEffect();
1434 if (dstOutput != mPrimaryOutput) {
1435 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1436 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001437 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001438 }
1439 }
1440}
1441
1442
Eric Laurentcaf7f482014-11-25 17:50:47 -08001443status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1444 audio_io_handle_t *input,
1445 audio_session_t session,
1446 uint32_t samplingRate,
1447 audio_format_t format,
1448 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001449 audio_input_flags_t flags,
1450 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001451{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001452 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1453 "session %d, flags %#x",
1454 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001455
Eric Laurentcaf7f482014-11-25 17:50:47 -08001456 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001457 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001458 audio_devices_t device;
1459 // handle legacy remote submix case where the address was not always specified
1460 String8 address = String8("");
Eric Laurent5dbe4712014-09-19 19:04:57 -07001461 bool isSoundTrigger = false;
Eric Laurentc447ded2015-01-06 08:47:05 -08001462 audio_source_t inputSource = attr->source;
1463 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001464 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001465
Eric Laurentc447ded2015-01-06 08:47:05 -08001466 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1467 inputSource = AUDIO_SOURCE_MIC;
1468 }
1469 halInputSource = inputSource;
1470
1471 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001472 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
1473 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1474 address = String8(attr->tags + strlen("addr="));
1475 ssize_t index = mPolicyMixes.indexOfKey(address);
1476 if (index < 0) {
1477 ALOGW("getInputForAttr() no policy for address %s", address.string());
1478 return BAD_VALUE;
1479 }
Eric Laurentc722f302014-12-10 11:21:49 -08001480 if (mPolicyMixes[index]->mMix.mMixType != MIX_TYPE_PLAYERS) {
1481 ALOGW("getInputForAttr() bad policy mix type for address %s", address.string());
1482 return BAD_VALUE;
1483 }
1484 policyMix = &mPolicyMixes[index]->mMix;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001485 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001486 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001487 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001488 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001489 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001490 return BAD_VALUE;
1491 }
Eric Laurentc722f302014-12-10 11:21:49 -08001492 if (policyMix != NULL) {
1493 address = policyMix->mRegistrationId;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001494 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1495 // there is an external policy, but this input is attached to a mix of recorders,
1496 // meaning it receives audio injected into the framework, so the recorder doesn't
1497 // know about it and is therefore considered "legacy"
1498 *inputType = API_INPUT_LEGACY;
1499 } else {
1500 // recording a mix of players defined by an external policy, we're rerouting for
1501 // an external policy
1502 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1503 }
Eric Laurentc722f302014-12-10 11:21:49 -08001504 } else if (audio_is_remote_submix_device(device)) {
1505 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001506 *inputType = API_INPUT_MIX_CAPTURE;
1507 } else {
1508 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001509 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001510 // adapt channel selection to input source
Eric Laurentc447ded2015-01-06 08:47:05 -08001511 switch (inputSource) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001512 case AUDIO_SOURCE_VOICE_UPLINK:
1513 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1514 break;
1515 case AUDIO_SOURCE_VOICE_DOWNLINK:
1516 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1517 break;
1518 case AUDIO_SOURCE_VOICE_CALL:
1519 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1520 break;
1521 default:
1522 break;
1523 }
Eric Laurentc447ded2015-01-06 08:47:05 -08001524 if (inputSource == AUDIO_SOURCE_HOTWORD) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001525 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1526 if (index >= 0) {
1527 *input = mSoundTriggerSessions.valueFor(session);
1528 isSoundTrigger = true;
1529 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1530 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
1531 } else {
1532 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1533 }
Eric Laurent5dbe4712014-09-19 19:04:57 -07001534 }
1535 }
1536
Eric Laurent275e8e92014-11-30 15:14:47 -08001537 sp<IOProfile> profile = getInputProfile(device, address,
1538 samplingRate, format, channelMask,
1539 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001540 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001541 //retry without flags
1542 audio_input_flags_t log_flags = flags;
1543 flags = AUDIO_INPUT_FLAG_NONE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001544 profile = getInputProfile(device, address,
1545 samplingRate, format, channelMask,
1546 flags);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001547 if (profile == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001548 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1549 "format %#x, channelMask 0x%X, flags %#x",
Eric Laurent5dbe4712014-09-19 19:04:57 -07001550 device, samplingRate, format, channelMask, log_flags);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001551 return BAD_VALUE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001552 }
Eric Laurente552edb2014-03-10 17:42:56 -07001553 }
1554
1555 if (profile->mModule->mHandle == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001556 ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName);
1557 return NO_INIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001558 }
1559
1560 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1561 config.sample_rate = samplingRate;
1562 config.channel_mask = channelMask;
1563 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001564
Eric Laurentcf2c0212014-07-25 16:20:43 -07001565 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001566 input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001567 &config,
1568 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001569 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001570 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001571 flags);
1572
1573 // only accept input with the exact requested set of parameters
Eric Laurentcaf7f482014-11-25 17:50:47 -08001574 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001575 (samplingRate != config.sample_rate) ||
1576 (format != config.format) ||
1577 (channelMask != config.channel_mask)) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001578 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001579 samplingRate, format, channelMask);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001580 if (*input != AUDIO_IO_HANDLE_NONE) {
1581 mpClientInterface->closeInput(*input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001582 }
Eric Laurentcaf7f482014-11-25 17:50:47 -08001583 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001584 }
1585
Eric Laurent1f2f2232014-06-02 12:01:23 -07001586 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurentc447ded2015-01-06 08:47:05 -08001587 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001588 inputDesc->mRefCount = 0;
1589 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001590 inputDesc->mSamplingRate = samplingRate;
1591 inputDesc->mFormat = format;
1592 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001593 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001594 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001595 inputDesc->mIsSoundTrigger = isSoundTrigger;
Eric Laurentc722f302014-12-10 11:21:49 -08001596 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001597
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001598 ALOGV("getInputForAttr() returns input type = %d", inputType);
1599
Eric Laurentcaf7f482014-11-25 17:50:47 -08001600 addInput(*input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001601 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcaf7f482014-11-25 17:50:47 -08001602 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001603}
1604
Eric Laurent4dc68062014-07-28 17:26:49 -07001605status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1606 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001607{
1608 ALOGV("startInput() input %d", input);
1609 ssize_t index = mInputs.indexOfKey(input);
1610 if (index < 0) {
1611 ALOGW("startInput() unknown input %d", input);
1612 return BAD_VALUE;
1613 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001614 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001615
Eric Laurentc722f302014-12-10 11:21:49 -08001616 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001617 if (index < 0) {
1618 ALOGW("startInput() unknown session %d on input %d", session, input);
1619 return BAD_VALUE;
1620 }
1621
Glenn Kasten74a8e252014-07-24 14:09:55 -07001622 // virtual input devices are compatible with other input devices
1623 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1624
1625 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001626 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001627 if (activeInput != 0 && activeInput != input) {
1628
1629 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1630 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001631 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001632 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001633 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurentc722f302014-12-10 11:21:49 -08001634 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1635 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001636 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001637 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001638 return INVALID_OPERATION;
1639 }
1640 }
1641 }
1642
Glenn Kasten74a8e252014-07-24 14:09:55 -07001643 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001644 if (activeInputsCount() == 0) {
1645 SoundTrigger::setCaptureState(true);
1646 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001647 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001648
Eric Laurentc722f302014-12-10 11:21:49 -08001649 // automatically enable the remote submix output when input is started if not
1650 // used by a policy mix of type MIX_TYPE_RECORDERS
Glenn Kasten74a8e252014-07-24 14:09:55 -07001651 // For remote submix (a virtual device), we open only one input per capture request.
1652 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001653 String8 address = String8("");
1654 if (inputDesc->mPolicyMix == NULL) {
1655 address = String8("0");
1656 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1657 address = inputDesc->mPolicyMix->mRegistrationId;
1658 }
1659 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001660 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001661 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1662 address);
1663 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001664 }
Eric Laurente552edb2014-03-10 17:42:56 -07001665 }
1666
Eric Laurente552edb2014-03-10 17:42:56 -07001667 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1668
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001669 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001670 return NO_ERROR;
1671}
1672
Eric Laurent4dc68062014-07-28 17:26:49 -07001673status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1674 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001675{
1676 ALOGV("stopInput() input %d", input);
1677 ssize_t index = mInputs.indexOfKey(input);
1678 if (index < 0) {
1679 ALOGW("stopInput() unknown input %d", input);
1680 return BAD_VALUE;
1681 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001682 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001683
Eric Laurentc722f302014-12-10 11:21:49 -08001684 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001685 if (index < 0) {
1686 ALOGW("stopInput() unknown session %d on input %d", session, input);
1687 return BAD_VALUE;
1688 }
1689
Eric Laurente552edb2014-03-10 17:42:56 -07001690 if (inputDesc->mRefCount == 0) {
1691 ALOGW("stopInput() input %d already stopped", input);
1692 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001693 }
1694
1695 inputDesc->mRefCount--;
1696 if (inputDesc->mRefCount == 0) {
1697
Eric Laurentc722f302014-12-10 11:21:49 -08001698 // automatically disable the remote submix output when input is stopped if not
1699 // used by a policy mix of type MIX_TYPE_RECORDERS
Eric Laurente552edb2014-03-10 17:42:56 -07001700 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001701 String8 address = String8("");
1702 if (inputDesc->mPolicyMix == NULL) {
1703 address = String8("0");
1704 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1705 address = inputDesc->mPolicyMix->mRegistrationId;
1706 }
1707 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001708 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001709 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1710 address);
1711 }
Eric Laurente552edb2014-03-10 17:42:56 -07001712 }
1713
Eric Laurent1c333e22014-05-20 10:48:17 -07001714 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001715
1716 if (activeInputsCount() == 0) {
1717 SoundTrigger::setCaptureState(false);
1718 }
Eric Laurente552edb2014-03-10 17:42:56 -07001719 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001720 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001721}
1722
Eric Laurent4dc68062014-07-28 17:26:49 -07001723void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1724 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001725{
1726 ALOGV("releaseInput() %d", input);
1727 ssize_t index = mInputs.indexOfKey(input);
1728 if (index < 0) {
1729 ALOGW("releaseInput() releasing unknown input %d", input);
1730 return;
1731 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001732 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1733 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001734
Eric Laurentc722f302014-12-10 11:21:49 -08001735 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001736 if (index < 0) {
1737 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1738 return;
1739 }
Eric Laurentc722f302014-12-10 11:21:49 -08001740 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001741 if (inputDesc->mOpenRefCount == 0) {
1742 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1743 return;
1744 }
1745 inputDesc->mOpenRefCount--;
1746 if (inputDesc->mOpenRefCount > 0) {
1747 ALOGV("releaseInput() exit > 0");
1748 return;
1749 }
1750
Eric Laurent05b90f82014-08-27 15:32:29 -07001751 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001752 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001753 ALOGV("releaseInput() exit");
1754}
1755
Eric Laurentd4692962014-05-05 18:13:44 -07001756void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001757 bool patchRemoved = false;
1758
Eric Laurentd4692962014-05-05 18:13:44 -07001759 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001760 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1761 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1762 if (patch_index >= 0) {
1763 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1764 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1765 mAudioPatches.removeItemsAt(patch_index);
1766 patchRemoved = true;
1767 }
Eric Laurentd4692962014-05-05 18:13:44 -07001768 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1769 }
1770 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001771 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001772
1773 if (patchRemoved) {
1774 mpClientInterface->onAudioPatchListUpdate();
1775 }
Eric Laurentd4692962014-05-05 18:13:44 -07001776}
1777
Eric Laurente0720872014-03-11 09:30:41 -07001778void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001779 int indexMin,
1780 int indexMax)
1781{
1782 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1783 if (indexMin < 0 || indexMin >= indexMax) {
1784 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1785 return;
1786 }
1787 mStreams[stream].mIndexMin = indexMin;
1788 mStreams[stream].mIndexMax = indexMax;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001789 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1790 if (stream == AUDIO_STREAM_MUSIC) {
1791 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1792 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1793 }
Eric Laurente552edb2014-03-10 17:42:56 -07001794}
1795
Eric Laurente0720872014-03-11 09:30:41 -07001796status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001797 int index,
1798 audio_devices_t device)
1799{
1800
1801 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1802 return BAD_VALUE;
1803 }
1804 if (!audio_is_output_device(device)) {
1805 return BAD_VALUE;
1806 }
1807
1808 // Force max volume if stream cannot be muted
1809 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1810
1811 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1812 stream, device, index);
1813
1814 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1815 // clear all device specific values
1816 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1817 mStreams[stream].mIndexCur.clear();
1818 }
1819 mStreams[stream].mIndexCur.add(device, index);
1820
Eric Laurent31551f82014-10-10 18:21:56 -07001821 // update volume on all outputs whose current device is also selected by the same
1822 // strategy as the device specified by the caller
1823 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001824
1825
1826 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1827 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1828 if (stream == AUDIO_STREAM_MUSIC) {
1829 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1830 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1831 }
1832 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1833 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001834 return NO_ERROR;
1835 }
Eric Laurente552edb2014-03-10 17:42:56 -07001836 status_t status = NO_ERROR;
1837 for (size_t i = 0; i < mOutputs.size(); i++) {
1838 audio_devices_t curDevice =
1839 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001840 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001841 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1842 if (volStatus != NO_ERROR) {
1843 status = volStatus;
1844 }
1845 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001846 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1847 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1848 index, mOutputs.keyAt(i), curDevice);
1849 }
Eric Laurente552edb2014-03-10 17:42:56 -07001850 }
1851 return status;
1852}
1853
Eric Laurente0720872014-03-11 09:30:41 -07001854status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001855 int *index,
1856 audio_devices_t device)
1857{
1858 if (index == NULL) {
1859 return BAD_VALUE;
1860 }
1861 if (!audio_is_output_device(device)) {
1862 return BAD_VALUE;
1863 }
1864 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1865 // the strategy the stream belongs to.
1866 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1867 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1868 }
1869 device = getDeviceForVolume(device);
1870
1871 *index = mStreams[stream].getVolumeIndex(device);
1872 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1873 return NO_ERROR;
1874}
1875
Eric Laurente0720872014-03-11 09:30:41 -07001876audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001877 const SortedVector<audio_io_handle_t>& outputs)
1878{
1879 // select one output among several suitable for global effects.
1880 // The priority is as follows:
1881 // 1: An offloaded output. If the effect ends up not being offloadable,
1882 // AudioFlinger will invalidate the track and the offloaded output
1883 // will be closed causing the effect to be moved to a PCM output.
1884 // 2: A deep buffer output
1885 // 3: the first output in the list
1886
1887 if (outputs.size() == 0) {
1888 return 0;
1889 }
1890
1891 audio_io_handle_t outputOffloaded = 0;
1892 audio_io_handle_t outputDeepBuffer = 0;
1893
1894 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001895 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001896 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001897 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1898 outputOffloaded = outputs[i];
1899 }
1900 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1901 outputDeepBuffer = outputs[i];
1902 }
1903 }
1904
1905 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1906 outputOffloaded, outputDeepBuffer);
1907 if (outputOffloaded != 0) {
1908 return outputOffloaded;
1909 }
1910 if (outputDeepBuffer != 0) {
1911 return outputDeepBuffer;
1912 }
1913
1914 return outputs[0];
1915}
1916
Eric Laurente0720872014-03-11 09:30:41 -07001917audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001918{
1919 // apply simple rule where global effects are attached to the same output as MUSIC streams
1920
Eric Laurent3b73df72014-03-11 09:06:29 -07001921 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001922 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1923 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1924
1925 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1926 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1927 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1928
1929 return output;
1930}
1931
Eric Laurente0720872014-03-11 09:30:41 -07001932status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001933 audio_io_handle_t io,
1934 uint32_t strategy,
1935 int session,
1936 int id)
1937{
1938 ssize_t index = mOutputs.indexOfKey(io);
1939 if (index < 0) {
1940 index = mInputs.indexOfKey(io);
1941 if (index < 0) {
1942 ALOGW("registerEffect() unknown io %d", io);
1943 return INVALID_OPERATION;
1944 }
1945 }
1946
1947 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1948 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1949 desc->name, desc->memoryUsage);
1950 return INVALID_OPERATION;
1951 }
1952 mTotalEffectsMemory += desc->memoryUsage;
1953 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1954 desc->name, io, strategy, session, id);
1955 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1956
Eric Laurent1f2f2232014-06-02 12:01:23 -07001957 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1958 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1959 effectDesc->mIo = io;
1960 effectDesc->mStrategy = (routing_strategy)strategy;
1961 effectDesc->mSession = session;
1962 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001963
Eric Laurent1f2f2232014-06-02 12:01:23 -07001964 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001965
1966 return NO_ERROR;
1967}
1968
Eric Laurente0720872014-03-11 09:30:41 -07001969status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001970{
1971 ssize_t index = mEffects.indexOfKey(id);
1972 if (index < 0) {
1973 ALOGW("unregisterEffect() unknown effect ID %d", id);
1974 return INVALID_OPERATION;
1975 }
1976
Eric Laurent1f2f2232014-06-02 12:01:23 -07001977 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001978
Eric Laurent1f2f2232014-06-02 12:01:23 -07001979 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001980
Eric Laurent1f2f2232014-06-02 12:01:23 -07001981 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001982 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001983 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1984 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001985 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001986 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001987 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001988 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001989
1990 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001991
1992 return NO_ERROR;
1993}
1994
Eric Laurente0720872014-03-11 09:30:41 -07001995status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001996{
1997 ssize_t index = mEffects.indexOfKey(id);
1998 if (index < 0) {
1999 ALOGW("unregisterEffect() unknown effect ID %d", id);
2000 return INVALID_OPERATION;
2001 }
2002
2003 return setEffectEnabled(mEffects.valueAt(index), enabled);
2004}
2005
Eric Laurent1f2f2232014-06-02 12:01:23 -07002006status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07002007{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002008 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07002009 ALOGV("setEffectEnabled(%s) effect already %s",
2010 enabled?"true":"false", enabled?"enabled":"disabled");
2011 return INVALID_OPERATION;
2012 }
2013
2014 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002015 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002016 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002017 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07002018 return INVALID_OPERATION;
2019 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002020 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002021 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
2022 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002023 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07002024 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002025 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
2026 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002027 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002028 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002029 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
2030 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002031 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07002032 return NO_ERROR;
2033}
2034
Eric Laurente0720872014-03-11 09:30:41 -07002035bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07002036{
2037 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002038 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
2039 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
2040 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002041 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002042 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07002043 return true;
2044 }
2045 }
2046 return false;
2047}
2048
Eric Laurente0720872014-03-11 09:30:41 -07002049bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002050{
2051 nsecs_t sysTime = systemTime();
2052 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002053 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07002054 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002055 return true;
2056 }
2057 }
2058 return false;
2059}
2060
Eric Laurente0720872014-03-11 09:30:41 -07002061bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07002062 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002063{
2064 nsecs_t sysTime = systemTime();
2065 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002066 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002067 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002068 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurentc722f302014-12-10 11:21:49 -08002069 // do not consider re routing (when the output is going to a dynamic policy)
2070 // as "remote playback"
2071 if (outputDesc->mPolicyMix == NULL) {
Jean-Michel Trivi1767df72014-12-09 18:11:49 -08002072 return true;
2073 }
Eric Laurente552edb2014-03-10 17:42:56 -07002074 }
2075 }
2076 return false;
2077}
2078
Eric Laurente0720872014-03-11 09:30:41 -07002079bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002080{
2081 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002082 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurenta34c9ce2014-12-19 11:16:32 -08002083 if (inputDescriptor->mRefCount == 0) {
2084 continue;
2085 }
2086 if (inputDescriptor->mInputSource == (int)source) {
Eric Laurente552edb2014-03-10 17:42:56 -07002087 return true;
2088 }
Eric Laurenta34c9ce2014-12-19 11:16:32 -08002089 // AUDIO_SOURCE_HOTWORD is equivalent to AUDIO_SOURCE_VOICE_RECOGNITION only if it
2090 // corresponds to an active capture triggered by a hardware hotword recognition
2091 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) &&
2092 (inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD)) {
2093 // FIXME: we should not assume that the first session is the active one and keep
2094 // activity count per session. Same in startInput().
2095 ssize_t index = mSoundTriggerSessions.indexOfKey(inputDescriptor->mSessions.itemAt(0));
2096 if (index >= 0) {
2097 return true;
2098 }
2099 }
Eric Laurente552edb2014-03-10 17:42:56 -07002100 }
2101 return false;
2102}
2103
Eric Laurent275e8e92014-11-30 15:14:47 -08002104// Register a list of custom mixes with their attributes and format.
2105// When a mix is registered, corresponding input and output profiles are
2106// added to the remote submix hw module. The profile contains only the
2107// parameters (sampling rate, format...) specified by the mix.
2108// The corresponding input remote submix device is also connected.
2109//
2110// When a remote submix device is connected, the address is checked to select the
2111// appropriate profile and the corresponding input or output stream is opened.
2112//
2113// When capture starts, getInputForAttr() will:
2114// - 1 look for a mix matching the address passed in attribtutes tags if any
2115// - 2 if none found, getDeviceForInputSource() will:
2116// - 2.1 look for a mix matching the attributes source
2117// - 2.2 if none found, default to device selection by policy rules
2118// At this time, the corresponding output remote submix device is also connected
2119// and active playback use cases can be transferred to this mix if needed when reconnecting
2120// after AudioTracks are invalidated
2121//
2122// When playback starts, getOutputForAttr() will:
2123// - 1 look for a mix matching the address passed in attribtutes tags if any
2124// - 2 if none found, look for a mix matching the attributes usage
2125// - 3 if none found, default to device and output selection by policy rules.
2126
2127status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2128{
2129 sp<HwModule> module;
2130 for (size_t i = 0; i < mHwModules.size(); i++) {
2131 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2132 mHwModules[i]->mHandle != 0) {
2133 module = mHwModules[i];
2134 break;
2135 }
2136 }
2137
2138 if (module == 0) {
2139 return INVALID_OPERATION;
2140 }
2141
2142 ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
2143
2144 for (size_t i = 0; i < mixes.size(); i++) {
2145 String8 address = mixes[i].mRegistrationId;
2146 ssize_t index = mPolicyMixes.indexOfKey(address);
2147 if (index >= 0) {
2148 ALOGE("registerPolicyMixes(): mix for address %s already registered", address.string());
2149 continue;
2150 }
2151 audio_config_t outputConfig = mixes[i].mFormat;
2152 audio_config_t inputConfig = mixes[i].mFormat;
2153 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2154 // stereo and let audio flinger do the channel conversion if needed.
2155 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2156 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2157 module->addOutputProfile(address, &outputConfig,
2158 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2159 module->addInputProfile(address, &inputConfig,
2160 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2161 sp<AudioPolicyMix> policyMix = new AudioPolicyMix();
2162 policyMix->mMix = mixes[i];
2163 mPolicyMixes.add(address, policyMix);
Eric Laurentc722f302014-12-10 11:21:49 -08002164 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002165 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002166 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2167 address.string());
2168 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002169 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002170 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2171 address.string());
2172 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002173 }
2174 return NO_ERROR;
2175}
2176
2177status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2178{
2179 sp<HwModule> module;
2180 for (size_t i = 0; i < mHwModules.size(); i++) {
2181 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2182 mHwModules[i]->mHandle != 0) {
2183 module = mHwModules[i];
2184 break;
2185 }
2186 }
2187
2188 if (module == 0) {
2189 return INVALID_OPERATION;
2190 }
2191
2192 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
2193
2194 for (size_t i = 0; i < mixes.size(); i++) {
2195 String8 address = mixes[i].mRegistrationId;
2196 ssize_t index = mPolicyMixes.indexOfKey(address);
2197 if (index < 0) {
2198 ALOGE("unregisterPolicyMixes(): mix for address %s not registered", address.string());
2199 continue;
2200 }
2201
2202 mPolicyMixes.removeItemsAt(index);
2203
Eric Laurentc722f302014-12-10 11:21:49 -08002204 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2205 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2206 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002207 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002208 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2209 address.string());
2210 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002211
2212 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2213 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2214 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002215 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08002216 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2217 address.string());
2218 }
2219 module->removeOutputProfile(address);
2220 module->removeInputProfile(address);
2221 }
2222 return NO_ERROR;
2223}
2224
Eric Laurente552edb2014-03-10 17:42:56 -07002225
Eric Laurente0720872014-03-11 09:30:41 -07002226status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002227{
2228 const size_t SIZE = 256;
2229 char buffer[SIZE];
2230 String8 result;
2231
2232 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2233 result.append(buffer);
2234
2235 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
2236 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002237 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
2238 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002239 snprintf(buffer, SIZE, " Force use for communications %d\n",
2240 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07002241 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002242 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07002243 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002244 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07002245 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002246 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07002247 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002248 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07002249 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002250 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2251 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
2252 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002253
Eric Laurent3a4311c2014-03-17 12:00:47 -07002254 snprintf(buffer, SIZE, " Available output devices:\n");
2255 result.append(buffer);
2256 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002257 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002258 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002259 }
2260 snprintf(buffer, SIZE, "\n Available input devices:\n");
2261 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07002262 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002263 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002264 }
Eric Laurente552edb2014-03-10 17:42:56 -07002265
2266 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
2267 write(fd, buffer, strlen(buffer));
2268 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002269 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002270 write(fd, buffer, strlen(buffer));
2271 mHwModules[i]->dump(fd);
2272 }
2273
2274 snprintf(buffer, SIZE, "\nOutputs dump:\n");
2275 write(fd, buffer, strlen(buffer));
2276 for (size_t i = 0; i < mOutputs.size(); i++) {
2277 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
2278 write(fd, buffer, strlen(buffer));
2279 mOutputs.valueAt(i)->dump(fd);
2280 }
2281
2282 snprintf(buffer, SIZE, "\nInputs dump:\n");
2283 write(fd, buffer, strlen(buffer));
2284 for (size_t i = 0; i < mInputs.size(); i++) {
2285 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
2286 write(fd, buffer, strlen(buffer));
2287 mInputs.valueAt(i)->dump(fd);
2288 }
2289
2290 snprintf(buffer, SIZE, "\nStreams dump:\n");
2291 write(fd, buffer, strlen(buffer));
2292 snprintf(buffer, SIZE,
2293 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
2294 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002295 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002296 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07002297 write(fd, buffer, strlen(buffer));
2298 mStreams[i].dump(fd);
2299 }
2300
2301 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2302 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2303 write(fd, buffer, strlen(buffer));
2304
2305 snprintf(buffer, SIZE, "Registered effects:\n");
2306 write(fd, buffer, strlen(buffer));
2307 for (size_t i = 0; i < mEffects.size(); i++) {
2308 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2309 write(fd, buffer, strlen(buffer));
2310 mEffects.valueAt(i)->dump(fd);
2311 }
2312
Eric Laurent4d416952014-08-10 14:07:09 -07002313 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2314 write(fd, buffer, strlen(buffer));
2315 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2316 mAudioPatches[i]->dump(fd, 2, i);
2317 }
Eric Laurente552edb2014-03-10 17:42:56 -07002318
2319 return NO_ERROR;
2320}
2321
2322// This function checks for the parameters which can be offloaded.
2323// This can be enhanced depending on the capability of the DSP and policy
2324// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002325bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002326{
2327 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002328 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002329 offloadInfo.sample_rate, offloadInfo.channel_mask,
2330 offloadInfo.format,
2331 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2332 offloadInfo.has_video);
2333
2334 // Check if offload has been disabled
2335 char propValue[PROPERTY_VALUE_MAX];
2336 if (property_get("audio.offload.disable", propValue, "0")) {
2337 if (atoi(propValue) != 0) {
2338 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2339 return false;
2340 }
2341 }
2342
2343 // Check if stream type is music, then only allow offload as of now.
2344 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2345 {
2346 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2347 return false;
2348 }
2349
2350 //TODO: enable audio offloading with video when ready
2351 if (offloadInfo.has_video)
2352 {
2353 ALOGV("isOffloadSupported: has_video == true, returning false");
2354 return false;
2355 }
2356
2357 //If duration is less than minimum value defined in property, return false
2358 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2359 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2360 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2361 return false;
2362 }
2363 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2364 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2365 return false;
2366 }
2367
2368 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2369 // creating an offloaded track and tearing it down immediately after start when audioflinger
2370 // detects there is an active non offloadable effect.
2371 // FIXME: We should check the audio session here but we do not have it in this context.
2372 // This may prevent offloading in rare situations where effects are left active by apps
2373 // in the background.
2374 if (isNonOffloadableEffectEnabled()) {
2375 return false;
2376 }
2377
2378 // See if there is a profile to support this.
2379 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002380 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002381 offloadInfo.sample_rate,
2382 offloadInfo.format,
2383 offloadInfo.channel_mask,
2384 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002385 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2386 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002387}
2388
Eric Laurent6a94d692014-05-20 11:18:06 -07002389status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2390 audio_port_type_t type,
2391 unsigned int *num_ports,
2392 struct audio_port *ports,
2393 unsigned int *generation)
2394{
2395 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2396 generation == NULL) {
2397 return BAD_VALUE;
2398 }
2399 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2400 if (ports == NULL) {
2401 *num_ports = 0;
2402 }
2403
2404 size_t portsWritten = 0;
2405 size_t portsMax = *num_ports;
2406 *num_ports = 0;
2407 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2408 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2409 for (size_t i = 0;
2410 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2411 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2412 }
2413 *num_ports += mAvailableOutputDevices.size();
2414 }
2415 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2416 for (size_t i = 0;
2417 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2418 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2419 }
2420 *num_ports += mAvailableInputDevices.size();
2421 }
2422 }
2423 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2424 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2425 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2426 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2427 }
2428 *num_ports += mInputs.size();
2429 }
2430 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002431 size_t numOutputs = 0;
2432 for (size_t i = 0; i < mOutputs.size(); i++) {
2433 if (!mOutputs[i]->isDuplicated()) {
2434 numOutputs++;
2435 if (portsWritten < portsMax) {
2436 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2437 }
2438 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002439 }
Eric Laurent84c70242014-06-23 08:46:27 -07002440 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002441 }
2442 }
2443 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002444 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002445 return NO_ERROR;
2446}
2447
2448status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2449{
2450 return NO_ERROR;
2451}
2452
Eric Laurent1f2f2232014-06-02 12:01:23 -07002453sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002454 audio_port_handle_t id) const
2455{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002456 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002457 for (size_t i = 0; i < mOutputs.size(); i++) {
2458 outputDesc = mOutputs.valueAt(i);
2459 if (outputDesc->mId == id) {
2460 break;
2461 }
2462 }
2463 return outputDesc;
2464}
2465
Eric Laurent1f2f2232014-06-02 12:01:23 -07002466sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002467 audio_port_handle_t id) const
2468{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002469 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002470 for (size_t i = 0; i < mInputs.size(); i++) {
2471 inputDesc = mInputs.valueAt(i);
2472 if (inputDesc->mId == id) {
2473 break;
2474 }
2475 }
2476 return inputDesc;
2477}
2478
Eric Laurent1f2f2232014-06-02 12:01:23 -07002479sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2480 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002481{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002482 sp <HwModule> module;
2483
Eric Laurent6a94d692014-05-20 11:18:06 -07002484 for (size_t i = 0; i < mHwModules.size(); i++) {
2485 if (mHwModules[i]->mHandle == 0) {
2486 continue;
2487 }
2488 if (audio_is_output_device(device)) {
2489 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2490 {
2491 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2492 return mHwModules[i];
2493 }
2494 }
2495 } else {
2496 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2497 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2498 device & ~AUDIO_DEVICE_BIT_IN) {
2499 return mHwModules[i];
2500 }
2501 }
2502 }
2503 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002504 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002505}
2506
Eric Laurent1f2f2232014-06-02 12:01:23 -07002507sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002508{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002509 sp <HwModule> module;
2510
Eric Laurent1afeecb2014-05-14 08:52:28 -07002511 for (size_t i = 0; i < mHwModules.size(); i++)
2512 {
2513 if (strcmp(mHwModules[i]->mName, name) == 0) {
2514 return mHwModules[i];
2515 }
2516 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002517 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002518}
2519
Eric Laurentc2730ba2014-07-20 15:47:07 -07002520audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2521{
2522 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2523 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2524 return devices & mAvailableOutputDevices.types();
2525}
2526
2527audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2528{
2529 audio_module_handle_t primaryHandle =
2530 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2531 audio_devices_t devices = AUDIO_DEVICE_NONE;
2532 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2533 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2534 devices |= mAvailableInputDevices[i]->mDeviceType;
2535 }
2536 }
2537 return devices;
2538}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002539
Eric Laurent6a94d692014-05-20 11:18:06 -07002540status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2541 audio_patch_handle_t *handle,
2542 uid_t uid)
2543{
2544 ALOGV("createAudioPatch()");
2545
2546 if (handle == NULL || patch == NULL) {
2547 return BAD_VALUE;
2548 }
2549 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2550
Eric Laurent874c42872014-08-08 15:13:39 -07002551 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2552 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2553 return BAD_VALUE;
2554 }
2555 // only one source per audio patch supported for now
2556 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002557 return INVALID_OPERATION;
2558 }
Eric Laurent874c42872014-08-08 15:13:39 -07002559
2560 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002561 return INVALID_OPERATION;
2562 }
Eric Laurent874c42872014-08-08 15:13:39 -07002563 for (size_t i = 0; i < patch->num_sinks; i++) {
2564 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2565 return INVALID_OPERATION;
2566 }
2567 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002568
2569 sp<AudioPatch> patchDesc;
2570 ssize_t index = mAudioPatches.indexOfKey(*handle);
2571
Eric Laurent6a94d692014-05-20 11:18:06 -07002572 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2573 patch->sources[0].role,
2574 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002575#if LOG_NDEBUG == 0
2576 for (size_t i = 0; i < patch->num_sinks; i++) {
2577 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2578 patch->sinks[i].role,
2579 patch->sinks[i].type);
2580 }
2581#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002582
2583 if (index >= 0) {
2584 patchDesc = mAudioPatches.valueAt(index);
2585 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2586 mUidCached, patchDesc->mUid, uid);
2587 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2588 return INVALID_OPERATION;
2589 }
2590 } else {
2591 *handle = 0;
2592 }
2593
2594 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002595 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002596 if (outputDesc == NULL) {
2597 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2598 return BAD_VALUE;
2599 }
Eric Laurent84c70242014-06-23 08:46:27 -07002600 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2601 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002602 if (patchDesc != 0) {
2603 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2604 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2605 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2606 return BAD_VALUE;
2607 }
2608 }
Eric Laurent874c42872014-08-08 15:13:39 -07002609 DeviceVector devices;
2610 for (size_t i = 0; i < patch->num_sinks; i++) {
2611 // Only support mix to devices connection
2612 // TODO add support for mix to mix connection
2613 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2614 ALOGV("createAudioPatch() source mix but sink is not a device");
2615 return INVALID_OPERATION;
2616 }
2617 sp<DeviceDescriptor> devDesc =
2618 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2619 if (devDesc == 0) {
2620 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2621 return BAD_VALUE;
2622 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002623
Eric Laurent874c42872014-08-08 15:13:39 -07002624 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002625 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002626 patch->sources[0].sample_rate,
2627 NULL, // updatedSamplingRate
2628 patch->sources[0].format,
2629 patch->sources[0].channel_mask,
2630 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2631 ALOGV("createAudioPatch() profile not supported for device %08x",
2632 devDesc->mDeviceType);
2633 return INVALID_OPERATION;
2634 }
2635 devices.add(devDesc);
2636 }
2637 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002638 return INVALID_OPERATION;
2639 }
Eric Laurent874c42872014-08-08 15:13:39 -07002640
Eric Laurent6a94d692014-05-20 11:18:06 -07002641 // TODO: reconfigure output format and channels here
2642 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002643 devices.types(), outputDesc->mIoHandle);
2644 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002645 index = mAudioPatches.indexOfKey(*handle);
2646 if (index >= 0) {
2647 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2648 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2649 }
2650 patchDesc = mAudioPatches.valueAt(index);
2651 patchDesc->mUid = uid;
2652 ALOGV("createAudioPatch() success");
2653 } else {
2654 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2655 return INVALID_OPERATION;
2656 }
2657 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2658 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2659 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002660 // only one sink supported when connecting an input device to a mix
2661 if (patch->num_sinks > 1) {
2662 return INVALID_OPERATION;
2663 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002664 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002665 if (inputDesc == NULL) {
2666 return BAD_VALUE;
2667 }
2668 if (patchDesc != 0) {
2669 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2670 return BAD_VALUE;
2671 }
2672 }
2673 sp<DeviceDescriptor> devDesc =
2674 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2675 if (devDesc == 0) {
2676 return BAD_VALUE;
2677 }
2678
Eric Laurent84c70242014-06-23 08:46:27 -07002679 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002680 devDesc->mAddress,
2681 patch->sinks[0].sample_rate,
2682 NULL, /*updatedSampleRate*/
2683 patch->sinks[0].format,
2684 patch->sinks[0].channel_mask,
2685 // FIXME for the parameter type,
2686 // and the NONE
2687 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002688 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002689 return INVALID_OPERATION;
2690 }
2691 // TODO: reconfigure output format and channels here
2692 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002693 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002694 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002695 index = mAudioPatches.indexOfKey(*handle);
2696 if (index >= 0) {
2697 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2698 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2699 }
2700 patchDesc = mAudioPatches.valueAt(index);
2701 patchDesc->mUid = uid;
2702 ALOGV("createAudioPatch() success");
2703 } else {
2704 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2705 return INVALID_OPERATION;
2706 }
2707 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2708 // device to device connection
2709 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002710 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002711 return BAD_VALUE;
2712 }
2713 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002714 sp<DeviceDescriptor> srcDeviceDesc =
2715 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002716 if (srcDeviceDesc == 0) {
2717 return BAD_VALUE;
2718 }
Eric Laurent874c42872014-08-08 15:13:39 -07002719
Eric Laurent6a94d692014-05-20 11:18:06 -07002720 //update source and sink with our own data as the data passed in the patch may
2721 // be incomplete.
2722 struct audio_patch newPatch = *patch;
2723 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002724
Eric Laurent874c42872014-08-08 15:13:39 -07002725 for (size_t i = 0; i < patch->num_sinks; i++) {
2726 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2727 ALOGV("createAudioPatch() source device but one sink is not a device");
2728 return INVALID_OPERATION;
2729 }
2730
2731 sp<DeviceDescriptor> sinkDeviceDesc =
2732 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2733 if (sinkDeviceDesc == 0) {
2734 return BAD_VALUE;
2735 }
2736 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2737
2738 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2739 // only one sink supported when connected devices across HW modules
2740 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002741 return INVALID_OPERATION;
2742 }
Eric Laurent874c42872014-08-08 15:13:39 -07002743 SortedVector<audio_io_handle_t> outputs =
2744 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2745 mOutputs);
2746 // if the sink device is reachable via an opened output stream, request to go via
2747 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002748 audio_io_handle_t output = selectOutput(outputs,
2749 AUDIO_OUTPUT_FLAG_NONE,
2750 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002751 if (output != AUDIO_IO_HANDLE_NONE) {
2752 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2753 if (outputDesc->isDuplicated()) {
2754 return INVALID_OPERATION;
2755 }
2756 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2757 newPatch.num_sources = 2;
2758 }
Eric Laurent83b88082014-06-20 18:31:16 -07002759 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002760 }
2761 // TODO: check from routing capabilities in config file and other conflicting patches
2762
2763 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2764 if (index >= 0) {
2765 afPatchHandle = patchDesc->mAfPatchHandle;
2766 }
2767
2768 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2769 &afPatchHandle,
2770 0);
2771 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2772 status, afPatchHandle);
2773 if (status == NO_ERROR) {
2774 if (index < 0) {
2775 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2776 &newPatch, uid);
2777 addAudioPatch(patchDesc->mHandle, patchDesc);
2778 } else {
2779 patchDesc->mPatch = newPatch;
2780 }
2781 patchDesc->mAfPatchHandle = afPatchHandle;
2782 *handle = patchDesc->mHandle;
2783 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002784 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002785 } else {
2786 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2787 status);
2788 return INVALID_OPERATION;
2789 }
2790 } else {
2791 return BAD_VALUE;
2792 }
2793 } else {
2794 return BAD_VALUE;
2795 }
2796 return NO_ERROR;
2797}
2798
2799status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2800 uid_t uid)
2801{
2802 ALOGV("releaseAudioPatch() patch %d", handle);
2803
2804 ssize_t index = mAudioPatches.indexOfKey(handle);
2805
2806 if (index < 0) {
2807 return BAD_VALUE;
2808 }
2809 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2810 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2811 mUidCached, patchDesc->mUid, uid);
2812 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2813 return INVALID_OPERATION;
2814 }
2815
2816 struct audio_patch *patch = &patchDesc->mPatch;
2817 patchDesc->mUid = mUidCached;
2818 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002819 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002820 if (outputDesc == NULL) {
2821 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2822 return BAD_VALUE;
2823 }
2824
2825 setOutputDevice(outputDesc->mIoHandle,
2826 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2827 true,
2828 0,
2829 NULL);
2830 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2831 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002832 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002833 if (inputDesc == NULL) {
2834 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2835 return BAD_VALUE;
2836 }
2837 setInputDevice(inputDesc->mIoHandle,
2838 getNewInputDevice(inputDesc->mIoHandle),
2839 true,
2840 NULL);
2841 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2842 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2843 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2844 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2845 status, patchDesc->mAfPatchHandle);
2846 removeAudioPatch(patchDesc->mHandle);
2847 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002848 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002849 } else {
2850 return BAD_VALUE;
2851 }
2852 } else {
2853 return BAD_VALUE;
2854 }
2855 return NO_ERROR;
2856}
2857
2858status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2859 struct audio_patch *patches,
2860 unsigned int *generation)
2861{
2862 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2863 generation == NULL) {
2864 return BAD_VALUE;
2865 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002866 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002867 *num_patches, patches, mAudioPatches.size());
2868 if (patches == NULL) {
2869 *num_patches = 0;
2870 }
2871
2872 size_t patchesWritten = 0;
2873 size_t patchesMax = *num_patches;
2874 for (size_t i = 0;
2875 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2876 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2877 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002878 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002879 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2880 }
2881 *num_patches = mAudioPatches.size();
2882
2883 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002884 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002885 return NO_ERROR;
2886}
2887
Eric Laurente1715a42014-05-20 11:30:42 -07002888status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002889{
Eric Laurente1715a42014-05-20 11:30:42 -07002890 ALOGV("setAudioPortConfig()");
2891
2892 if (config == NULL) {
2893 return BAD_VALUE;
2894 }
2895 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2896 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002897 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2898 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002899 }
2900
Eric Laurenta121f902014-06-03 13:32:54 -07002901 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002902 if (config->type == AUDIO_PORT_TYPE_MIX) {
2903 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002904 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002905 if (outputDesc == NULL) {
2906 return BAD_VALUE;
2907 }
Eric Laurent84c70242014-06-23 08:46:27 -07002908 ALOG_ASSERT(!outputDesc->isDuplicated(),
2909 "setAudioPortConfig() called on duplicated output %d",
2910 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002911 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002912 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002913 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002914 if (inputDesc == NULL) {
2915 return BAD_VALUE;
2916 }
Eric Laurenta121f902014-06-03 13:32:54 -07002917 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002918 } else {
2919 return BAD_VALUE;
2920 }
2921 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2922 sp<DeviceDescriptor> deviceDesc;
2923 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2924 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2925 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2926 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2927 } else {
2928 return BAD_VALUE;
2929 }
2930 if (deviceDesc == NULL) {
2931 return BAD_VALUE;
2932 }
Eric Laurenta121f902014-06-03 13:32:54 -07002933 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002934 } else {
2935 return BAD_VALUE;
2936 }
2937
Eric Laurenta121f902014-06-03 13:32:54 -07002938 struct audio_port_config backupConfig;
2939 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2940 if (status == NO_ERROR) {
2941 struct audio_port_config newConfig;
2942 audioPortConfig->toAudioPortConfig(&newConfig, config);
2943 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002944 }
Eric Laurenta121f902014-06-03 13:32:54 -07002945 if (status != NO_ERROR) {
2946 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002947 }
Eric Laurente1715a42014-05-20 11:30:42 -07002948
2949 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002950}
2951
2952void AudioPolicyManager::clearAudioPatches(uid_t uid)
2953{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002954 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002955 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2956 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002957 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002958 }
2959 }
2960}
2961
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002962status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2963 audio_io_handle_t *ioHandle,
2964 audio_devices_t *device)
2965{
2966 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2967 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002968 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002969
2970 mSoundTriggerSessions.add(*session, *ioHandle);
2971
2972 return NO_ERROR;
2973}
2974
2975status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2976{
2977 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2978 if (index < 0) {
2979 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2980 return BAD_VALUE;
2981 }
2982
2983 mSoundTriggerSessions.removeItem(session);
2984 return NO_ERROR;
2985}
2986
Eric Laurent6a94d692014-05-20 11:18:06 -07002987status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2988 const sp<AudioPatch>& patch)
2989{
2990 ssize_t index = mAudioPatches.indexOfKey(handle);
2991
2992 if (index >= 0) {
2993 ALOGW("addAudioPatch() patch %d already in", handle);
2994 return ALREADY_EXISTS;
2995 }
2996 mAudioPatches.add(handle, patch);
2997 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2998 "sink handle %d",
2999 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
3000 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
3001 return NO_ERROR;
3002}
3003
3004status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
3005{
3006 ssize_t index = mAudioPatches.indexOfKey(handle);
3007
3008 if (index < 0) {
3009 ALOGW("removeAudioPatch() patch %d not in", handle);
3010 return ALREADY_EXISTS;
3011 }
3012 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
3013 mAudioPatches.valueAt(index)->mAfPatchHandle);
3014 mAudioPatches.removeItemsAt(index);
3015 return NO_ERROR;
3016}
3017
Eric Laurente552edb2014-03-10 17:42:56 -07003018// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003019// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003020// ----------------------------------------------------------------------------
3021
Eric Laurent3a4311c2014-03-17 12:00:47 -07003022uint32_t AudioPolicyManager::nextUniqueId()
3023{
3024 return android_atomic_inc(&mNextUniqueId);
3025}
3026
Eric Laurent6a94d692014-05-20 11:18:06 -07003027uint32_t AudioPolicyManager::nextAudioPortGeneration()
3028{
3029 return android_atomic_inc(&mAudioPortGeneration);
3030}
3031
Eric Laurente0720872014-03-11 09:30:41 -07003032AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003033 :
3034#ifdef AUDIO_POLICY_TEST
3035 Thread(false),
3036#endif //AUDIO_POLICY_TEST
3037 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07003038 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07003039 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
3040 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003041 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07003042 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003043 mAudioPortGeneration(1),
3044 mBeaconMuteRefCount(0),
3045 mBeaconPlayingRefCount(0),
3046 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003047{
Eric Laurent6a94d692014-05-20 11:18:06 -07003048 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07003049 mpClientInterface = clientInterface;
3050
Eric Laurent3b73df72014-03-11 09:06:29 -07003051 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
3052 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003053 }
3054
Eric Laurent1afeecb2014-05-14 08:52:28 -07003055 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07003056 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
3057 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
3058 ALOGE("could not load audio policy configuration file, setting defaults");
3059 defaultAudioPolicyConfig();
3060 }
3061 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003062 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003063
3064 // must be done after reading the policy
3065 initializeVolumeCurves();
3066
3067 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003068 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3069 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003070 for (size_t i = 0; i < mHwModules.size(); i++) {
3071 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
3072 if (mHwModules[i]->mHandle == 0) {
3073 ALOGW("could not open HW module %s", mHwModules[i]->mName);
3074 continue;
3075 }
3076 // open all output streams needed to access attached devices
3077 // except for direct output streams that are only opened when they are actually
3078 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003079 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003080 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3081 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003082 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003083
Eric Laurent3a4311c2014-03-17 12:00:47 -07003084 if (outProfile->mSupportedDevices.isEmpty()) {
3085 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
3086 continue;
3087 }
3088
Eric Laurentd78f1532014-09-16 16:38:20 -07003089 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
3090 continue;
3091 }
Eric Laurent83b88082014-06-20 18:31:16 -07003092 audio_devices_t profileType = outProfile->mSupportedDevices.types();
3093 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
3094 profileType = mDefaultOutputDevice->mDeviceType;
3095 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07003096 // chose first device present in mSupportedDevices also part of
3097 // outputDeviceTypes
3098 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3099 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
3100 if ((profileType & outputDeviceTypes) != 0) {
3101 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003102 }
Eric Laurente552edb2014-03-10 17:42:56 -07003103 }
3104 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003105 if ((profileType & outputDeviceTypes) == 0) {
3106 continue;
3107 }
3108 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
3109
3110 outputDesc->mDevice = profileType;
3111 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3112 config.sample_rate = outputDesc->mSamplingRate;
3113 config.channel_mask = outputDesc->mChannelMask;
3114 config.format = outputDesc->mFormat;
3115 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3116 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
3117 &output,
3118 &config,
3119 &outputDesc->mDevice,
3120 String8(""),
3121 &outputDesc->mLatency,
3122 outputDesc->mFlags);
3123
3124 if (status != NO_ERROR) {
3125 ALOGW("Cannot open output stream for device %08x on hw module %s",
3126 outputDesc->mDevice,
3127 mHwModules[i]->mName);
3128 } else {
3129 outputDesc->mSamplingRate = config.sample_rate;
3130 outputDesc->mChannelMask = config.channel_mask;
3131 outputDesc->mFormat = config.format;
3132
3133 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3134 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
3135 ssize_t index =
3136 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
3137 // give a valid ID to an attached device once confirmed it is reachable
3138 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
3139 mAvailableOutputDevices[index]->mId = nextUniqueId();
3140 mAvailableOutputDevices[index]->mModule = mHwModules[i];
3141 }
3142 }
3143 if (mPrimaryOutput == 0 &&
3144 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
3145 mPrimaryOutput = output;
3146 }
3147 addOutput(output, outputDesc);
3148 setOutputDevice(output,
3149 outputDesc->mDevice,
3150 true);
3151 }
Eric Laurente552edb2014-03-10 17:42:56 -07003152 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003153 // open input streams needed to access attached devices to validate
3154 // mAvailableInputDevices list
3155 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3156 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003157 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003158
Eric Laurent3a4311c2014-03-17 12:00:47 -07003159 if (inProfile->mSupportedDevices.isEmpty()) {
3160 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
3161 continue;
3162 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003163 // chose first device present in mSupportedDevices also part of
3164 // inputDeviceTypes
3165 audio_devices_t profileType = AUDIO_DEVICE_NONE;
3166 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3167 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
3168 if (profileType & inputDeviceTypes) {
3169 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003170 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003171 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003172 if ((profileType & inputDeviceTypes) == 0) {
3173 continue;
3174 }
3175 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
3176
3177 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
3178 inputDesc->mDevice = profileType;
3179
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003180 // find the address
3181 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3182 // the inputs vector must be of size 1, but we don't want to crash here
3183 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3184 : String8("");
3185 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3186 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3187
Eric Laurentd78f1532014-09-16 16:38:20 -07003188 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3189 config.sample_rate = inputDesc->mSamplingRate;
3190 config.channel_mask = inputDesc->mChannelMask;
3191 config.format = inputDesc->mFormat;
3192 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3193 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
3194 &input,
3195 &config,
3196 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003197 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003198 AUDIO_SOURCE_MIC,
3199 AUDIO_INPUT_FLAG_NONE);
3200
3201 if (status == NO_ERROR) {
3202 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3203 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
3204 ssize_t index =
3205 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
3206 // give a valid ID to an attached device once confirmed it is reachable
3207 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
3208 mAvailableInputDevices[index]->mId = nextUniqueId();
3209 mAvailableInputDevices[index]->mModule = mHwModules[i];
3210 }
3211 }
3212 mpClientInterface->closeInput(input);
3213 } else {
3214 ALOGW("Cannot open input stream for device %08x on hw module %s",
3215 inputDesc->mDevice,
3216 mHwModules[i]->mName);
3217 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003218 }
3219 }
3220 // make sure all attached devices have been allocated a unique ID
3221 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
3222 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003223 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003224 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3225 continue;
3226 }
3227 i++;
3228 }
3229 for (size_t i = 0; i < mAvailableInputDevices.size();) {
3230 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003231 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003232 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3233 continue;
3234 }
3235 i++;
3236 }
3237 // make sure default device is reachable
3238 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003239 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003240 }
Eric Laurente552edb2014-03-10 17:42:56 -07003241
3242 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3243
3244 updateDevicesAndOutputs();
3245
3246#ifdef AUDIO_POLICY_TEST
3247 if (mPrimaryOutput != 0) {
3248 AudioParameter outputCmd = AudioParameter();
3249 outputCmd.addInt(String8("set_id"), 0);
3250 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3251
3252 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3253 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003254 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3255 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003256 mTestLatencyMs = 0;
3257 mCurOutput = 0;
3258 mDirectOutput = false;
3259 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3260 mTestOutputs[i] = 0;
3261 }
3262
3263 const size_t SIZE = 256;
3264 char buffer[SIZE];
3265 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3266 run(buffer, ANDROID_PRIORITY_AUDIO);
3267 }
3268#endif //AUDIO_POLICY_TEST
3269}
3270
Eric Laurente0720872014-03-11 09:30:41 -07003271AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003272{
3273#ifdef AUDIO_POLICY_TEST
3274 exit();
3275#endif //AUDIO_POLICY_TEST
3276 for (size_t i = 0; i < mOutputs.size(); i++) {
3277 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003278 }
3279 for (size_t i = 0; i < mInputs.size(); i++) {
3280 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003281 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003282 mAvailableOutputDevices.clear();
3283 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003284 mOutputs.clear();
3285 mInputs.clear();
3286 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003287}
3288
Eric Laurente0720872014-03-11 09:30:41 -07003289status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003290{
3291 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
3292}
3293
3294#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003295bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003296{
3297 ALOGV("entering threadLoop()");
3298 while (!exitPending())
3299 {
3300 String8 command;
3301 int valueInt;
3302 String8 value;
3303
3304 Mutex::Autolock _l(mLock);
3305 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3306
3307 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3308 AudioParameter param = AudioParameter(command);
3309
3310 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3311 valueInt != 0) {
3312 ALOGV("Test command %s received", command.string());
3313 String8 target;
3314 if (param.get(String8("target"), target) != NO_ERROR) {
3315 target = "Manager";
3316 }
3317 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3318 param.remove(String8("test_cmd_policy_output"));
3319 mCurOutput = valueInt;
3320 }
3321 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3322 param.remove(String8("test_cmd_policy_direct"));
3323 if (value == "false") {
3324 mDirectOutput = false;
3325 } else if (value == "true") {
3326 mDirectOutput = true;
3327 }
3328 }
3329 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3330 param.remove(String8("test_cmd_policy_input"));
3331 mTestInput = valueInt;
3332 }
3333
3334 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3335 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003336 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003337 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003338 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003339 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003340 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003341 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003342 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003343 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003344 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003345 if (target == "Manager") {
3346 mTestFormat = format;
3347 } else if (mTestOutputs[mCurOutput] != 0) {
3348 AudioParameter outputParam = AudioParameter();
3349 outputParam.addInt(String8("format"), format);
3350 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3351 }
3352 }
3353 }
3354 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3355 param.remove(String8("test_cmd_policy_channels"));
3356 int channels = 0;
3357
3358 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003359 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003360 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003361 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003362 }
3363 if (channels != 0) {
3364 if (target == "Manager") {
3365 mTestChannels = channels;
3366 } else if (mTestOutputs[mCurOutput] != 0) {
3367 AudioParameter outputParam = AudioParameter();
3368 outputParam.addInt(String8("channels"), channels);
3369 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3370 }
3371 }
3372 }
3373 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3374 param.remove(String8("test_cmd_policy_sampleRate"));
3375 if (valueInt >= 0 && valueInt <= 96000) {
3376 int samplingRate = valueInt;
3377 if (target == "Manager") {
3378 mTestSamplingRate = samplingRate;
3379 } else if (mTestOutputs[mCurOutput] != 0) {
3380 AudioParameter outputParam = AudioParameter();
3381 outputParam.addInt(String8("sampling_rate"), samplingRate);
3382 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3383 }
3384 }
3385 }
3386
3387 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3388 param.remove(String8("test_cmd_policy_reopen"));
3389
Eric Laurent1f2f2232014-06-02 12:01:23 -07003390 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003391 mpClientInterface->closeOutput(mPrimaryOutput);
3392
3393 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3394
Eric Laurente552edb2014-03-10 17:42:56 -07003395 mOutputs.removeItem(mPrimaryOutput);
3396
Eric Laurent1f2f2232014-06-02 12:01:23 -07003397 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003398 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003399 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3400 config.sample_rate = outputDesc->mSamplingRate;
3401 config.channel_mask = outputDesc->mChannelMask;
3402 config.format = outputDesc->mFormat;
3403 status_t status = mpClientInterface->openOutput(moduleHandle,
3404 &mPrimaryOutput,
3405 &config,
3406 &outputDesc->mDevice,
3407 String8(""),
3408 &outputDesc->mLatency,
3409 outputDesc->mFlags);
3410 if (status != NO_ERROR) {
3411 ALOGE("Failed to reopen hardware output stream, "
3412 "samplingRate: %d, format %d, channels %d",
3413 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003414 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003415 outputDesc->mSamplingRate = config.sample_rate;
3416 outputDesc->mChannelMask = config.channel_mask;
3417 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003418 AudioParameter outputCmd = AudioParameter();
3419 outputCmd.addInt(String8("set_id"), 0);
3420 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3421 addOutput(mPrimaryOutput, outputDesc);
3422 }
3423 }
3424
3425
3426 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3427 }
3428 }
3429 return false;
3430}
3431
Eric Laurente0720872014-03-11 09:30:41 -07003432void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003433{
3434 {
3435 AutoMutex _l(mLock);
3436 requestExit();
3437 mWaitWorkCV.signal();
3438 }
3439 requestExitAndWait();
3440}
3441
Eric Laurente0720872014-03-11 09:30:41 -07003442int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003443{
3444 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3445 if (output == mTestOutputs[i]) return i;
3446 }
3447 return 0;
3448}
3449#endif //AUDIO_POLICY_TEST
3450
3451// ---
3452
Eric Laurent1f2f2232014-06-02 12:01:23 -07003453void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003454{
Eric Laurent1c333e22014-05-20 10:48:17 -07003455 outputDesc->mIoHandle = output;
3456 outputDesc->mId = nextUniqueId();
3457 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003458 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003459}
3460
Eric Laurent1f2f2232014-06-02 12:01:23 -07003461void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003462{
Eric Laurent1c333e22014-05-20 10:48:17 -07003463 inputDesc->mIoHandle = input;
3464 inputDesc->mId = nextUniqueId();
3465 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003466 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003467}
Eric Laurente552edb2014-03-10 17:42:56 -07003468
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003469void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003470 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003471 const String8 address /*in*/,
3472 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003473 sp<DeviceDescriptor> devDesc =
3474 desc->mProfile->mSupportedDevices.getDevice(device, address);
3475 if (devDesc != 0) {
3476 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3477 desc->mIoHandle, address.string());
3478 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003479 }
3480}
3481
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003482status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003483 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003484 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003485 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003486{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003487 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003488 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003489 // erase all current sample rates, formats and channel masks
3490 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003491
Eric Laurent3b73df72014-03-11 09:06:29 -07003492 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003493 // first list already open outputs that can be routed to this device
3494 for (size_t i = 0; i < mOutputs.size(); i++) {
3495 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003496 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003497 if (!deviceDistinguishesOnAddress(device)) {
3498 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3499 outputs.add(mOutputs.keyAt(i));
3500 } else {
3501 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003502 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003503 }
Eric Laurente552edb2014-03-10 17:42:56 -07003504 }
3505 }
3506 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003507 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003508 for (size_t i = 0; i < mHwModules.size(); i++)
3509 {
3510 if (mHwModules[i]->mHandle == 0) {
3511 continue;
3512 }
3513 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3514 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003515 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3516 if (profile->mSupportedDevices.types() & device) {
3517 if (!deviceDistinguishesOnAddress(device) ||
3518 address == profile->mSupportedDevices[0]->mAddress) {
3519 profiles.add(profile);
3520 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3521 }
Eric Laurente552edb2014-03-10 17:42:56 -07003522 }
3523 }
3524 }
3525
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003526 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3527
Eric Laurente552edb2014-03-10 17:42:56 -07003528 if (profiles.isEmpty() && outputs.isEmpty()) {
3529 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3530 return BAD_VALUE;
3531 }
3532
3533 // open outputs for matching profiles if needed. Direct outputs are also opened to
3534 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3535 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003536 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003537
3538 // nothing to do if one output is already opened for this profile
3539 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003540 for (j = 0; j < outputs.size(); j++) {
3541 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003542 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003543 // matching profile: save the sample rates, format and channel masks supported
3544 // by the profile in our device descriptor
3545 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003546 break;
3547 }
3548 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003549 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003550 continue;
3551 }
3552
Eric Laurent83b88082014-06-20 18:31:16 -07003553 ALOGV("opening output for device %08x with params %s profile %p",
3554 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003555 desc = new AudioOutputDescriptor(profile);
3556 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003557 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3558 config.sample_rate = desc->mSamplingRate;
3559 config.channel_mask = desc->mChannelMask;
3560 config.format = desc->mFormat;
3561 config.offload_info.sample_rate = desc->mSamplingRate;
3562 config.offload_info.channel_mask = desc->mChannelMask;
3563 config.offload_info.format = desc->mFormat;
3564 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3565 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3566 &output,
3567 &config,
3568 &desc->mDevice,
3569 address,
3570 &desc->mLatency,
3571 desc->mFlags);
3572 if (status == NO_ERROR) {
3573 desc->mSamplingRate = config.sample_rate;
3574 desc->mChannelMask = config.channel_mask;
3575 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003576
Eric Laurentd4692962014-05-05 18:13:44 -07003577 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003578 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003579 char *param = audio_device_address_to_parameter(device, address);
3580 mpClientInterface->setParameters(output, String8(param));
3581 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003582 }
3583
Eric Laurentd4692962014-05-05 18:13:44 -07003584 // Here is where we step through and resolve any "dynamic" fields
3585 String8 reply;
3586 char *value;
3587 if (profile->mSamplingRates[0] == 0) {
3588 reply = mpClientInterface->getParameters(output,
3589 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003590 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003591 reply.string());
3592 value = strpbrk((char *)reply.string(), "=");
3593 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003594 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003595 }
Eric Laurentd4692962014-05-05 18:13:44 -07003596 }
3597 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3598 reply = mpClientInterface->getParameters(output,
3599 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003600 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003601 reply.string());
3602 value = strpbrk((char *)reply.string(), "=");
3603 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003604 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003605 }
Eric Laurentd4692962014-05-05 18:13:44 -07003606 }
3607 if (profile->mChannelMasks[0] == 0) {
3608 reply = mpClientInterface->getParameters(output,
3609 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003610 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003611 reply.string());
3612 value = strpbrk((char *)reply.string(), "=");
3613 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003614 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003615 }
Eric Laurentd4692962014-05-05 18:13:44 -07003616 }
3617 if (((profile->mSamplingRates[0] == 0) &&
3618 (profile->mSamplingRates.size() < 2)) ||
3619 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3620 (profile->mFormats.size() < 2)) ||
3621 ((profile->mChannelMasks[0] == 0) &&
3622 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003623 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003624 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003625 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003626 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3627 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003628 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003629 config.sample_rate = profile->pickSamplingRate();
3630 config.channel_mask = profile->pickChannelMask();
3631 config.format = profile->pickFormat();
3632 config.offload_info.sample_rate = config.sample_rate;
3633 config.offload_info.channel_mask = config.channel_mask;
3634 config.offload_info.format = config.format;
3635 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3636 &output,
3637 &config,
3638 &desc->mDevice,
3639 address,
3640 &desc->mLatency,
3641 desc->mFlags);
3642 if (status == NO_ERROR) {
3643 desc->mSamplingRate = config.sample_rate;
3644 desc->mChannelMask = config.channel_mask;
3645 desc->mFormat = config.format;
3646 } else {
3647 output = AUDIO_IO_HANDLE_NONE;
3648 }
Eric Laurentd4692962014-05-05 18:13:44 -07003649 }
3650
Eric Laurentcf2c0212014-07-25 16:20:43 -07003651 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003652 addOutput(output, desc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003653 if (deviceDistinguishesOnAddress(device) && address != "0") {
3654 ssize_t index = mPolicyMixes.indexOfKey(address);
3655 if (index >= 0) {
3656 mPolicyMixes[index]->mOutput = desc;
Eric Laurentc722f302014-12-10 11:21:49 -08003657 desc->mPolicyMix = &mPolicyMixes[index]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08003658 } else {
3659 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3660 address.string());
3661 }
Eric Laurentc722f302014-12-10 11:21:49 -08003662 } else if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
3663 // no duplicated output for direct outputs and
3664 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003665 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003666
Eric Laurentd4692962014-05-05 18:13:44 -07003667 // set initial stream volume for device
3668 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003669
Eric Laurentd4692962014-05-05 18:13:44 -07003670 //TODO: configure audio effect output stage here
3671
3672 // open a duplicating output thread for the new output and the primary output
3673 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3674 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003675 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003676 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003677 sp<AudioOutputDescriptor> dupOutputDesc =
3678 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003679 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3680 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3681 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3682 dupOutputDesc->mFormat = desc->mFormat;
3683 dupOutputDesc->mChannelMask = desc->mChannelMask;
3684 dupOutputDesc->mLatency = desc->mLatency;
3685 addOutput(duplicatedOutput, dupOutputDesc);
3686 applyStreamVolumes(duplicatedOutput, device, 0, true);
3687 } else {
3688 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3689 mPrimaryOutput, output);
3690 mpClientInterface->closeOutput(output);
3691 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003692 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003693 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003694 }
Eric Laurente552edb2014-03-10 17:42:56 -07003695 }
3696 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003697 } else {
3698 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003699 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003700 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003701 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003702 profiles.removeAt(profile_index);
3703 profile_index--;
3704 } else {
3705 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003706 devDesc->importAudioPort(profile);
3707
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003708 if (deviceDistinguishesOnAddress(device)) {
3709 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3710 device, address.string());
3711 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3712 NULL/*patch handle*/, address.string());
3713 }
Eric Laurente552edb2014-03-10 17:42:56 -07003714 ALOGV("checkOutputsForDevice(): adding output %d", output);
3715 }
3716 }
3717
3718 if (profiles.isEmpty()) {
3719 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3720 return BAD_VALUE;
3721 }
Eric Laurentd4692962014-05-05 18:13:44 -07003722 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003723 // check if one opened output is not needed any more after disconnecting one device
3724 for (size_t i = 0; i < mOutputs.size(); i++) {
3725 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003726 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003727 // exact match on device
3728 if (deviceDistinguishesOnAddress(device) &&
3729 (desc->mProfile->mSupportedDevices.types() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003730 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08003731 } else if (!(desc->mProfile->mSupportedDevices.types()
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003732 & mAvailableOutputDevices.types())) {
3733 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3734 mOutputs.keyAt(i));
3735 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003736 }
Eric Laurente552edb2014-03-10 17:42:56 -07003737 }
3738 }
Eric Laurentd4692962014-05-05 18:13:44 -07003739 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003740 for (size_t i = 0; i < mHwModules.size(); i++)
3741 {
3742 if (mHwModules[i]->mHandle == 0) {
3743 continue;
3744 }
3745 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3746 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003747 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003748 if (profile->mSupportedDevices.types() & device) {
3749 ALOGV("checkOutputsForDevice(): "
3750 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003751 if (profile->mSamplingRates[0] == 0) {
3752 profile->mSamplingRates.clear();
3753 profile->mSamplingRates.add(0);
3754 }
3755 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3756 profile->mFormats.clear();
3757 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3758 }
3759 if (profile->mChannelMasks[0] == 0) {
3760 profile->mChannelMasks.clear();
3761 profile->mChannelMasks.add(0);
3762 }
3763 }
3764 }
3765 }
3766 }
3767 return NO_ERROR;
3768}
3769
Eric Laurentd4692962014-05-05 18:13:44 -07003770status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3771 audio_policy_dev_state_t state,
3772 SortedVector<audio_io_handle_t>& inputs,
3773 const String8 address)
3774{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003775 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003776 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3777 // first list already open inputs that can be routed to this device
3778 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3779 desc = mInputs.valueAt(input_index);
3780 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3781 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3782 inputs.add(mInputs.keyAt(input_index));
3783 }
3784 }
3785
3786 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003787 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003788 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3789 {
3790 if (mHwModules[module_idx]->mHandle == 0) {
3791 continue;
3792 }
3793 for (size_t profile_index = 0;
3794 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3795 profile_index++)
3796 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003797 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3798
3799 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3800 if (!deviceDistinguishesOnAddress(device) ||
3801 address == profile->mSupportedDevices[0]->mAddress) {
3802 profiles.add(profile);
3803 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3804 profile_index, module_idx);
3805 }
Eric Laurentd4692962014-05-05 18:13:44 -07003806 }
3807 }
3808 }
3809
3810 if (profiles.isEmpty() && inputs.isEmpty()) {
3811 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3812 return BAD_VALUE;
3813 }
3814
3815 // open inputs for matching profiles if needed. Direct inputs are also opened to
3816 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3817 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3818
Eric Laurent1c333e22014-05-20 10:48:17 -07003819 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003820 // nothing to do if one input is already opened for this profile
3821 size_t input_index;
3822 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3823 desc = mInputs.valueAt(input_index);
3824 if (desc->mProfile == profile) {
3825 break;
3826 }
3827 }
3828 if (input_index != mInputs.size()) {
3829 continue;
3830 }
3831
3832 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3833 desc = new AudioInputDescriptor(profile);
3834 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003835 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3836 config.sample_rate = desc->mSamplingRate;
3837 config.channel_mask = desc->mChannelMask;
3838 config.format = desc->mFormat;
3839 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3840 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3841 &input,
3842 &config,
3843 &desc->mDevice,
3844 address,
3845 AUDIO_SOURCE_MIC,
3846 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003847
Eric Laurentcf2c0212014-07-25 16:20:43 -07003848 if (status == NO_ERROR) {
3849 desc->mSamplingRate = config.sample_rate;
3850 desc->mChannelMask = config.channel_mask;
3851 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003852
Eric Laurentd4692962014-05-05 18:13:44 -07003853 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003854 char *param = audio_device_address_to_parameter(device, address);
3855 mpClientInterface->setParameters(input, String8(param));
3856 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003857 }
3858
3859 // Here is where we step through and resolve any "dynamic" fields
3860 String8 reply;
3861 char *value;
3862 if (profile->mSamplingRates[0] == 0) {
3863 reply = mpClientInterface->getParameters(input,
3864 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3865 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3866 reply.string());
3867 value = strpbrk((char *)reply.string(), "=");
3868 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003869 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003870 }
3871 }
3872 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3873 reply = mpClientInterface->getParameters(input,
3874 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3875 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3876 value = strpbrk((char *)reply.string(), "=");
3877 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003878 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003879 }
3880 }
3881 if (profile->mChannelMasks[0] == 0) {
3882 reply = mpClientInterface->getParameters(input,
3883 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3884 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3885 reply.string());
3886 value = strpbrk((char *)reply.string(), "=");
3887 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003888 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003889 }
3890 }
3891 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3892 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3893 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3894 ALOGW("checkInputsForDevice() direct input missing param");
3895 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003896 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003897 }
3898
3899 if (input != 0) {
3900 addInput(input, desc);
3901 }
3902 } // endif input != 0
3903
Eric Laurentcf2c0212014-07-25 16:20:43 -07003904 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003905 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003906 profiles.removeAt(profile_index);
3907 profile_index--;
3908 } else {
3909 inputs.add(input);
3910 ALOGV("checkInputsForDevice(): adding input %d", input);
3911 }
3912 } // end scan profiles
3913
3914 if (profiles.isEmpty()) {
3915 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3916 return BAD_VALUE;
3917 }
3918 } else {
3919 // Disconnect
3920 // check if one opened input is not needed any more after disconnecting one device
3921 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3922 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003923 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3924 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003925 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3926 mInputs.keyAt(input_index));
3927 inputs.add(mInputs.keyAt(input_index));
3928 }
3929 }
3930 // Clear any profiles associated with the disconnected device.
3931 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3932 if (mHwModules[module_index]->mHandle == 0) {
3933 continue;
3934 }
3935 for (size_t profile_index = 0;
3936 profile_index < mHwModules[module_index]->mInputProfiles.size();
3937 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003938 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003939 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003940 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003941 profile_index, module_index);
3942 if (profile->mSamplingRates[0] == 0) {
3943 profile->mSamplingRates.clear();
3944 profile->mSamplingRates.add(0);
3945 }
3946 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3947 profile->mFormats.clear();
3948 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3949 }
3950 if (profile->mChannelMasks[0] == 0) {
3951 profile->mChannelMasks.clear();
3952 profile->mChannelMasks.add(0);
3953 }
3954 }
3955 }
3956 }
3957 } // end disconnect
3958
3959 return NO_ERROR;
3960}
3961
3962
Eric Laurente0720872014-03-11 09:30:41 -07003963void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003964{
3965 ALOGV("closeOutput(%d)", output);
3966
Eric Laurent1f2f2232014-06-02 12:01:23 -07003967 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003968 if (outputDesc == NULL) {
3969 ALOGW("closeOutput() unknown output %d", output);
3970 return;
3971 }
3972
Eric Laurent275e8e92014-11-30 15:14:47 -08003973 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
3974 if (mPolicyMixes[i]->mOutput == outputDesc) {
3975 mPolicyMixes[i]->mOutput.clear();
3976 }
3977 }
3978
Eric Laurente552edb2014-03-10 17:42:56 -07003979 // look for duplicated outputs connected to the output being removed.
3980 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003981 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003982 if (dupOutputDesc->isDuplicated() &&
3983 (dupOutputDesc->mOutput1 == outputDesc ||
3984 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003985 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003986 if (dupOutputDesc->mOutput1 == outputDesc) {
3987 outputDesc2 = dupOutputDesc->mOutput2;
3988 } else {
3989 outputDesc2 = dupOutputDesc->mOutput1;
3990 }
3991 // As all active tracks on duplicated output will be deleted,
3992 // and as they were also referenced on the other output, the reference
3993 // count for their stream type must be adjusted accordingly on
3994 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003995 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003996 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003997 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003998 }
3999 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4000 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4001
4002 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004003 mOutputs.removeItem(duplicatedOutput);
4004 }
4005 }
4006
Eric Laurent05b90f82014-08-27 15:32:29 -07004007 nextAudioPortGeneration();
4008
4009 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4010 if (index >= 0) {
4011 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4012 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4013 mAudioPatches.removeItemsAt(index);
4014 mpClientInterface->onAudioPatchListUpdate();
4015 }
4016
Eric Laurente552edb2014-03-10 17:42:56 -07004017 AudioParameter param;
4018 param.add(String8("closing"), String8("true"));
4019 mpClientInterface->setParameters(output, param.toString());
4020
4021 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004022 mOutputs.removeItem(output);
4023 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004024}
4025
4026void AudioPolicyManager::closeInput(audio_io_handle_t input)
4027{
4028 ALOGV("closeInput(%d)", input);
4029
4030 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4031 if (inputDesc == NULL) {
4032 ALOGW("closeInput() unknown input %d", input);
4033 return;
4034 }
4035
Eric Laurent6a94d692014-05-20 11:18:06 -07004036 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004037
4038 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4039 if (index >= 0) {
4040 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4041 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4042 mAudioPatches.removeItemsAt(index);
4043 mpClientInterface->onAudioPatchListUpdate();
4044 }
4045
4046 mpClientInterface->closeInput(input);
4047 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004048}
4049
Eric Laurente0720872014-03-11 09:30:41 -07004050SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07004051 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004052{
4053 SortedVector<audio_io_handle_t> outputs;
4054
4055 ALOGVV("getOutputsForDevice() device %04x", device);
4056 for (size_t i = 0; i < openOutputs.size(); i++) {
4057 ALOGVV("output %d isDuplicated=%d device=%04x",
4058 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
4059 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4060 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4061 outputs.add(openOutputs.keyAt(i));
4062 }
4063 }
4064 return outputs;
4065}
4066
Eric Laurente0720872014-03-11 09:30:41 -07004067bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07004068 SortedVector<audio_io_handle_t>& outputs2)
4069{
4070 if (outputs1.size() != outputs2.size()) {
4071 return false;
4072 }
4073 for (size_t i = 0; i < outputs1.size(); i++) {
4074 if (outputs1[i] != outputs2[i]) {
4075 return false;
4076 }
4077 }
4078 return true;
4079}
4080
Eric Laurente0720872014-03-11 09:30:41 -07004081void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004082{
4083 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4084 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4085 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4086 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4087
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004088 // also take into account external policy-related changes: add all outputs which are
4089 // associated with policies in the "before" and "after" output vectors
4090 ALOGVV("checkOutputForStrategy(): policy related outputs");
4091 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
4092 const sp<AudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
4093 if (desc != 0 && desc->mPolicyMix != NULL) {
4094 srcOutputs.add(desc->mIoHandle);
4095 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4096 }
4097 }
4098 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
4099 const sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4100 if (desc != 0 && desc->mPolicyMix != NULL) {
4101 dstOutputs.add(desc->mIoHandle);
4102 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4103 }
4104 }
4105
Eric Laurente552edb2014-03-10 17:42:56 -07004106 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4107 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4108 strategy, srcOutputs[0], dstOutputs[0]);
4109 // mute strategy while moving tracks from one output to another
4110 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004111 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004112 if (desc->isStrategyActive(strategy)) {
4113 setStrategyMute(strategy, true, srcOutputs[i]);
4114 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
4115 }
4116 }
4117
4118 // Move effects associated to this strategy from previous output to new output
4119 if (strategy == STRATEGY_MEDIA) {
4120 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4121 SortedVector<audio_io_handle_t> moved;
4122 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004123 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4124 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4125 effectDesc->mIo != fxOutput) {
4126 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004127 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4128 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004129 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004130 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004131 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004132 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004133 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004134 }
4135 }
4136 }
4137 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004138 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004139 if (i == AUDIO_STREAM_PATCH) {
4140 continue;
4141 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004142 if (getStrategy((audio_stream_type_t)i) == strategy) {
4143 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004144 }
4145 }
4146 }
4147}
4148
Eric Laurente0720872014-03-11 09:30:41 -07004149void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004150{
Jon Eklund966095e2014-09-09 15:39:49 -05004151 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4152 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004153 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05004154 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4155 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004156 checkOutputForStrategy(STRATEGY_SONIFICATION);
4157 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004158 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004159 checkOutputForStrategy(STRATEGY_MEDIA);
4160 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004161 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004162}
4163
Eric Laurente0720872014-03-11 09:30:41 -07004164audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07004165{
Eric Laurente552edb2014-03-10 17:42:56 -07004166 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004167 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004168 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
4169 return mOutputs.keyAt(i);
4170 }
4171 }
4172
4173 return 0;
4174}
4175
Eric Laurente0720872014-03-11 09:30:41 -07004176void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004177{
Eric Laurente552edb2014-03-10 17:42:56 -07004178 audio_io_handle_t a2dpOutput = getA2dpOutput();
4179 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004180 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004181 return;
4182 }
4183
Eric Laurent3a4311c2014-03-17 12:00:47 -07004184 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004185 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4186 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4187 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004188 // suspend A2DP output if:
4189 // (NOT already suspended) &&
4190 // ((SCO device is connected &&
4191 // (forced usage for communication || for record is SCO))) ||
4192 // (phone state is ringing || in call)
4193 //
4194 // restore A2DP output if:
4195 // (Already suspended) &&
4196 // ((SCO device is NOT connected ||
4197 // (forced usage NOT for communication && NOT for record is SCO))) &&
4198 // (phone state is NOT ringing && NOT in call)
4199 //
4200 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004201 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004202 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
4203 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
4204 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
4205 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004206
4207 mpClientInterface->restoreOutput(a2dpOutput);
4208 mA2dpSuspended = false;
4209 }
4210 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004211 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004212 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4213 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
4214 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
4215 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004216
4217 mpClientInterface->suspendOutput(a2dpOutput);
4218 mA2dpSuspended = true;
4219 }
4220 }
4221}
4222
Eric Laurent1c333e22014-05-20 10:48:17 -07004223audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004224{
4225 audio_devices_t device = AUDIO_DEVICE_NONE;
4226
Eric Laurent1f2f2232014-06-02 12:01:23 -07004227 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004228
4229 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4230 if (index >= 0) {
4231 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4232 if (patchDesc->mUid != mUidCached) {
4233 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4234 outputDesc->device(), outputDesc->mPatchHandle);
4235 return outputDesc->device();
4236 }
4237 }
4238
Eric Laurente552edb2014-03-10 17:42:56 -07004239 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004240 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004241 // use device for strategy enforced audible
4242 // 2: we are in call or the strategy phone is active on the output:
4243 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004244 // 3: the strategy for enforced audible is active but not enforced on the output:
4245 // use the device for strategy enforced audible
4246 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004247 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05004248 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004249 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004250 // 6: the strategy accessibility is active on the output:
4251 // use device for strategy accessibility
4252 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004253 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004254 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004255 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004256 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004257 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05004258 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
4259 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004260 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4261 } else if (isInCall() ||
4262 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
4263 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05004264 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
4265 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004266 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
4267 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
4268 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
4269 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004270 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
4271 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004272 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
4273 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
4274 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
4275 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004276 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
4277 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004278 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
4279 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004280 }
4281
Eric Laurent1c333e22014-05-20 10:48:17 -07004282 ALOGV("getNewOutputDevice() selected device %x", device);
4283 return device;
4284}
4285
4286audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4287{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004288 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004289
4290 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4291 if (index >= 0) {
4292 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4293 if (patchDesc->mUid != mUidCached) {
4294 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4295 inputDesc->mDevice, inputDesc->mPatchHandle);
4296 return inputDesc->mDevice;
4297 }
4298 }
4299
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004300 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07004301
4302 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004303 return device;
4304}
4305
Eric Laurente0720872014-03-11 09:30:41 -07004306uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004307 return (uint32_t)getStrategy(stream);
4308}
4309
Eric Laurente0720872014-03-11 09:30:41 -07004310audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004311 // By checking the range of stream before calling getStrategy, we avoid
4312 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4313 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004314 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004315 return AUDIO_DEVICE_NONE;
4316 }
4317 audio_devices_t devices;
4318 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
4319 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4320 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4321 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004322 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07004323 if (outputDesc->isStrategyActive(strategy)) {
4324 devices = outputDesc->device();
4325 break;
4326 }
Eric Laurente552edb2014-03-10 17:42:56 -07004327 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004328
4329 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4330 and doesn't really need to.*/
4331 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4332 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4333 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4334 }
4335
Eric Laurente552edb2014-03-10 17:42:56 -07004336 return devices;
4337}
4338
Eric Laurente0720872014-03-11 09:30:41 -07004339AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004340 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004341
4342 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4343
Eric Laurente552edb2014-03-10 17:42:56 -07004344 // stream to strategy mapping
4345 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004346 case AUDIO_STREAM_VOICE_CALL:
4347 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004348 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004349 case AUDIO_STREAM_RING:
4350 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004351 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004352 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004353 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004354 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004355 return STRATEGY_DTMF;
4356 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004357 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004358 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004359 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4360 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004361 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004362 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004363 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004364 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004365 case AUDIO_STREAM_TTS:
4366 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004367 case AUDIO_STREAM_ACCESSIBILITY:
4368 return STRATEGY_ACCESSIBILITY;
4369 case AUDIO_STREAM_REROUTING:
4370 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004371 }
4372}
4373
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004374uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4375 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004376 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4377 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4378 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004379 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4380 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4381 }
4382
4383 // usage to strategy mapping
4384 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004385 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4386 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4387 return (uint32_t) STRATEGY_SONIFICATION;
4388 }
4389 if (isInCall()) {
4390 return (uint32_t) STRATEGY_PHONE;
4391 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004392 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004393
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004394 case AUDIO_USAGE_MEDIA:
4395 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004396 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4397 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4398 return (uint32_t) STRATEGY_MEDIA;
4399
4400 case AUDIO_USAGE_VOICE_COMMUNICATION:
4401 return (uint32_t) STRATEGY_PHONE;
4402
4403 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4404 return (uint32_t) STRATEGY_DTMF;
4405
4406 case AUDIO_USAGE_ALARM:
4407 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4408 return (uint32_t) STRATEGY_SONIFICATION;
4409
4410 case AUDIO_USAGE_NOTIFICATION:
4411 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4412 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4413 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4414 case AUDIO_USAGE_NOTIFICATION_EVENT:
4415 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4416
4417 case AUDIO_USAGE_UNKNOWN:
4418 default:
4419 return (uint32_t) STRATEGY_MEDIA;
4420 }
4421}
4422
Eric Laurente0720872014-03-11 09:30:41 -07004423void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004424 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004425 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004426 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4427 updateDevicesAndOutputs();
4428 break;
4429 default:
4430 break;
4431 }
4432}
4433
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004434bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4435 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4436 if (s == (size_t) streamToIgnore) {
4437 continue;
4438 }
4439 for (size_t i = 0; i < mOutputs.size(); i++) {
4440 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4441 if (outputDesc->mRefCount[s] != 0) {
4442 return true;
4443 }
4444 }
4445 }
4446 return false;
4447}
4448
4449uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4450 switch(event) {
4451 case STARTING_OUTPUT:
4452 mBeaconMuteRefCount++;
4453 break;
4454 case STOPPING_OUTPUT:
4455 if (mBeaconMuteRefCount > 0) {
4456 mBeaconMuteRefCount--;
4457 }
4458 break;
4459 case STARTING_BEACON:
4460 mBeaconPlayingRefCount++;
4461 break;
4462 case STOPPING_BEACON:
4463 if (mBeaconPlayingRefCount > 0) {
4464 mBeaconPlayingRefCount--;
4465 }
4466 break;
4467 }
4468
4469 if (mBeaconMuteRefCount > 0) {
4470 // any playback causes beacon to be muted
4471 return setBeaconMute(true);
4472 } else {
4473 // no other playback: unmute when beacon starts playing, mute when it stops
4474 return setBeaconMute(mBeaconPlayingRefCount == 0);
4475 }
4476}
4477
4478uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4479 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4480 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4481 // keep track of muted state to avoid repeating mute/unmute operations
4482 if (mBeaconMuted != mute) {
4483 // mute/unmute AUDIO_STREAM_TTS on all outputs
4484 ALOGV("\t muting %d", mute);
4485 uint32_t maxLatency = 0;
4486 for (size_t i = 0; i < mOutputs.size(); i++) {
4487 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4488 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4489 desc->mIoHandle,
4490 0 /*delay*/, AUDIO_DEVICE_NONE);
4491 const uint32_t latency = desc->latency() * 2;
4492 if (latency > maxLatency) {
4493 maxLatency = latency;
4494 }
4495 }
4496 mBeaconMuted = mute;
4497 return maxLatency;
4498 }
4499 return 0;
4500}
4501
Eric Laurente0720872014-03-11 09:30:41 -07004502audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004503 bool fromCache)
4504{
4505 uint32_t device = AUDIO_DEVICE_NONE;
4506
4507 if (fromCache) {
4508 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4509 strategy, mDeviceForStrategy[strategy]);
4510 return mDeviceForStrategy[strategy];
4511 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004512 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004513 switch (strategy) {
4514
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004515 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4516 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4517 if (!device) {
4518 ALOGE("getDeviceForStrategy() no device found for "\
4519 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4520 }
4521 break;
4522
Eric Laurente552edb2014-03-10 17:42:56 -07004523 case STRATEGY_SONIFICATION_RESPECTFUL:
4524 if (isInCall()) {
4525 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004526 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004527 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4528 // while media is playing on a remote device, use the the sonification behavior.
4529 // Note that we test this usecase before testing if media is playing because
4530 // the isStreamActive() method only informs about the activity of a stream, not
4531 // if it's for local playback. Note also that we use the same delay between both tests
4532 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004533 //user "safe" speaker if available instead of normal speaker to avoid triggering
4534 //other acoustic safety mechanisms for notification
4535 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4536 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004537 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004538 // while media is playing (or has recently played), use the same device
4539 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4540 } else {
4541 // when media is not playing anymore, fall back on the sonification behavior
4542 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004543 //user "safe" speaker if available instead of normal speaker to avoid triggering
4544 //other acoustic safety mechanisms for notification
4545 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4546 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004547 }
4548
4549 break;
4550
4551 case STRATEGY_DTMF:
4552 if (!isInCall()) {
4553 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4554 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4555 break;
4556 }
4557 // when in call, DTMF and PHONE strategies follow the same rules
4558 // FALL THROUGH
4559
4560 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004561 // Force use of only devices on primary output if:
4562 // - in call AND
4563 // - cannot route from voice call RX OR
4564 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4565 if (mPhoneState == AUDIO_MODE_IN_CALL) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004566 audio_devices_t txDevice =
4567 getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -07004568 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4569 if (((mAvailableInputDevices.types() &
4570 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4571 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004572 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004573 AUDIO_DEVICE_API_VERSION_3_0))) {
4574 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4575 }
4576 }
Eric Laurente552edb2014-03-10 17:42:56 -07004577 // for phone strategy, we first consider the forced use and then the available devices by order
4578 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004579 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4580 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004581 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004582 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004583 if (device) break;
4584 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004585 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004586 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004587 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004588 if (device) break;
4589 // if SCO device is requested but no SCO device is available, fall back to default case
4590 // FALL THROUGH
4591
4592 default: // FORCE_NONE
4593 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004594 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004595 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004596 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004597 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004598 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004599 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004600 if (device) break;
4601 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004602 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004603 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004604 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004605 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004606 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4607 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004608 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004609 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004610 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004611 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004612 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004613 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004614 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004615 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004616 if (device) break;
4617 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004618 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004619 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004620 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004621 if (device == AUDIO_DEVICE_NONE) {
4622 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4623 }
4624 break;
4625
Eric Laurent3b73df72014-03-11 09:06:29 -07004626 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004627 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4628 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004629 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004630 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004631 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004632 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004633 if (device) break;
4634 }
Eric Laurentcd71a692014-12-16 12:01:12 -08004635 if (!isInCall()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004636 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004637 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004638 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004639 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004640 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004641 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004642 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004643 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004644 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004645 if (device) break;
4646 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004647 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4648 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004649 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004650 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004651 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004652 if (device == AUDIO_DEVICE_NONE) {
4653 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4654 }
4655 break;
4656 }
4657 break;
4658
4659 case STRATEGY_SONIFICATION:
4660
4661 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4662 // handleIncallSonification().
4663 if (isInCall()) {
4664 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4665 break;
4666 }
4667 // FALL THROUGH
4668
4669 case STRATEGY_ENFORCED_AUDIBLE:
4670 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4671 // except:
4672 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4673 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4674
4675 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004676 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004677 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004678 if (device == AUDIO_DEVICE_NONE) {
4679 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4680 }
4681 }
4682 // The second device used for sonification is the same as the device used by media strategy
4683 // FALL THROUGH
4684
Eric Laurent223fd5c2014-11-11 13:43:36 -08004685 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4686 case STRATEGY_ACCESSIBILITY:
Eric Laurent066ceec2014-11-25 12:35:01 -08004687 if (strategy == STRATEGY_ACCESSIBILITY) {
4688 // do not route accessibility prompts to a digital output currently configured with a
4689 // compressed format as they would likely not be mixed and dropped.
4690 for (size_t i = 0; i < mOutputs.size(); i++) {
4691 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4692 audio_devices_t devices = desc->device() &
4693 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4694 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4695 devices != AUDIO_DEVICE_NONE) {
4696 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4697 }
4698 }
4699 }
4700 // FALL THROUGH
4701
Eric Laurent223fd5c2014-11-11 13:43:36 -08004702 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004703 case STRATEGY_MEDIA: {
4704 uint32_t device2 = AUDIO_DEVICE_NONE;
4705 if (strategy != STRATEGY_SONIFICATION) {
4706 // no sonification on remote submix (e.g. WFD)
Eric Laurent275e8e92014-11-30 15:14:47 -08004707 if (mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, String8("0")) != 0) {
4708 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
4709 }
Eric Laurente552edb2014-03-10 17:42:56 -07004710 }
4711 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004712 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004713 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004714 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004715 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004716 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004717 }
4718 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004719 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004720 }
4721 }
Hochi Huang327cb702014-09-21 09:47:31 +08004722 if ((device2 == AUDIO_DEVICE_NONE) &&
4723 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4724 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4725 }
Eric Laurente552edb2014-03-10 17:42:56 -07004726 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004727 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004728 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004729 if ((device2 == AUDIO_DEVICE_NONE)) {
4730 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4731 }
Eric Laurente552edb2014-03-10 17:42:56 -07004732 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004733 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004734 }
4735 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004736 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004737 }
4738 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004739 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004740 }
4741 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004742 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004743 }
4744 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4745 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004746 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004747 }
4748 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004749 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004750 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004751 }
4752 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004753 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004754 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004755 int device3 = AUDIO_DEVICE_NONE;
4756 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004757 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004758 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4759 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004760 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004761 }
Eric Laurente552edb2014-03-10 17:42:56 -07004762
Jungshik Jang839e4f32014-06-26 17:23:40 +09004763 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004764 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4765 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4766 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004767
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004768 // If hdmi system audio mode is on, remove speaker out of output list.
4769 if ((strategy == STRATEGY_MEDIA) &&
4770 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4771 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4772 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4773 }
4774
Eric Laurente552edb2014-03-10 17:42:56 -07004775 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004776 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004777 if (device == AUDIO_DEVICE_NONE) {
4778 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4779 }
4780 } break;
4781
4782 default:
4783 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4784 break;
4785 }
4786
4787 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4788 return device;
4789}
4790
Eric Laurente0720872014-03-11 09:30:41 -07004791void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004792{
4793 for (int i = 0; i < NUM_STRATEGIES; i++) {
4794 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4795 }
4796 mPreviousOutputs = mOutputs;
4797}
4798
Eric Laurent1f2f2232014-06-02 12:01:23 -07004799uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004800 audio_devices_t prevDevice,
4801 uint32_t delayMs)
4802{
4803 // mute/unmute strategies using an incompatible device combination
4804 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4805 // if unmuting, unmute only after the specified delay
4806 if (outputDesc->isDuplicated()) {
4807 return 0;
4808 }
4809
4810 uint32_t muteWaitMs = 0;
4811 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004812 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004813
4814 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4815 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004816 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004817 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4818 bool doMute = false;
4819
4820 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4821 doMute = true;
4822 outputDesc->mStrategyMutedByDevice[i] = true;
4823 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4824 doMute = true;
4825 outputDesc->mStrategyMutedByDevice[i] = false;
4826 }
Eric Laurent99401132014-05-07 19:48:15 -07004827 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004828 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004829 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004830 // skip output if it does not share any device with current output
4831 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4832 == AUDIO_DEVICE_NONE) {
4833 continue;
4834 }
4835 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4836 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4837 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4838 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4839 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004840 if (mute) {
4841 // FIXME: should not need to double latency if volume could be applied
4842 // immediately by the audioflinger mixer. We must account for the delay
4843 // between now and the next time the audioflinger thread for this output
4844 // will process a buffer (which corresponds to one buffer size,
4845 // usually 1/2 or 1/4 of the latency).
4846 if (muteWaitMs < desc->latency() * 2) {
4847 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004848 }
4849 }
4850 }
4851 }
4852 }
4853 }
4854
Eric Laurent99401132014-05-07 19:48:15 -07004855 // temporary mute output if device selection changes to avoid volume bursts due to
4856 // different per device volumes
4857 if (outputDesc->isActive() && (device != prevDevice)) {
4858 if (muteWaitMs < outputDesc->latency() * 2) {
4859 muteWaitMs = outputDesc->latency() * 2;
4860 }
4861 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4862 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004863 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004864 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004865 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004866 muteWaitMs *2, device);
4867 }
4868 }
4869 }
4870
Eric Laurente552edb2014-03-10 17:42:56 -07004871 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4872 if (muteWaitMs > delayMs) {
4873 muteWaitMs -= delayMs;
4874 usleep(muteWaitMs * 1000);
4875 return muteWaitMs;
4876 }
4877 return 0;
4878}
4879
Eric Laurente0720872014-03-11 09:30:41 -07004880uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004881 audio_devices_t device,
4882 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004883 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004884 audio_patch_handle_t *patchHandle,
4885 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004886{
4887 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004888 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004889 AudioParameter param;
4890 uint32_t muteWaitMs;
4891
4892 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004893 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4894 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004895 return muteWaitMs;
4896 }
4897 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4898 // output profile
4899 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004900 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004901 return 0;
4902 }
4903
4904 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004905 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004906
4907 audio_devices_t prevDevice = outputDesc->mDevice;
4908
4909 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4910
4911 if (device != AUDIO_DEVICE_NONE) {
4912 outputDesc->mDevice = device;
4913 }
4914 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4915
4916 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004917 // the requested device is AUDIO_DEVICE_NONE
4918 // OR the requested device is the same as current device
4919 // AND force is not specified
4920 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004921 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004922 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4923 outputDesc->mPatchHandle != 0) {
4924 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4925 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004926 return muteWaitMs;
4927 }
4928
4929 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004930
Eric Laurente552edb2014-03-10 17:42:56 -07004931 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004932 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004933 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004934 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004935 DeviceVector deviceList = (address == NULL) ?
4936 mAvailableOutputDevices.getDevicesFromType(device)
4937 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004938 if (!deviceList.isEmpty()) {
4939 struct audio_patch patch;
4940 outputDesc->toAudioPortConfig(&patch.sources[0]);
4941 patch.num_sources = 1;
4942 patch.num_sinks = 0;
4943 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4944 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004945 patch.num_sinks++;
4946 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004947 ssize_t index;
4948 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4949 index = mAudioPatches.indexOfKey(*patchHandle);
4950 } else {
4951 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4952 }
4953 sp< AudioPatch> patchDesc;
4954 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4955 if (index >= 0) {
4956 patchDesc = mAudioPatches.valueAt(index);
4957 afPatchHandle = patchDesc->mAfPatchHandle;
4958 }
4959
Eric Laurent1c333e22014-05-20 10:48:17 -07004960 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004961 &afPatchHandle,
4962 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004963 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4964 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004965 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004966 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004967 if (index < 0) {
4968 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4969 &patch, mUidCached);
4970 addAudioPatch(patchDesc->mHandle, patchDesc);
4971 } else {
4972 patchDesc->mPatch = patch;
4973 }
4974 patchDesc->mAfPatchHandle = afPatchHandle;
4975 patchDesc->mUid = mUidCached;
4976 if (patchHandle) {
4977 *patchHandle = patchDesc->mHandle;
4978 }
4979 outputDesc->mPatchHandle = patchDesc->mHandle;
4980 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004981 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004982 }
4983 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004984
4985 // inform all input as well
4986 for (size_t i = 0; i < mInputs.size(); i++) {
4987 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4988 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4989 AudioParameter inputCmd = AudioParameter();
4990 ALOGV("%s: inform input %d of device:%d", __func__,
4991 inputDescriptor->mIoHandle, device);
4992 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4993 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4994 inputCmd.toString(),
4995 delayMs);
4996 }
4997 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004998 }
Eric Laurente552edb2014-03-10 17:42:56 -07004999
5000 // update stream volumes according to new device
5001 applyStreamVolumes(output, device, delayMs);
5002
5003 return muteWaitMs;
5004}
5005
Eric Laurent1c333e22014-05-20 10:48:17 -07005006status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07005007 int delayMs,
5008 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005009{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005010 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07005011 ssize_t index;
5012 if (patchHandle) {
5013 index = mAudioPatches.indexOfKey(*patchHandle);
5014 } else {
5015 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
5016 }
5017 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005018 return INVALID_OPERATION;
5019 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005020 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5021 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005022 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
5023 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005024 removeAudioPatch(patchDesc->mHandle);
5025 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005026 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005027 return status;
5028}
5029
5030status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5031 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005032 bool force,
5033 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005034{
5035 status_t status = NO_ERROR;
5036
Eric Laurent1f2f2232014-06-02 12:01:23 -07005037 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005038 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5039 inputDesc->mDevice = device;
5040
5041 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5042 if (!deviceList.isEmpty()) {
5043 struct audio_patch patch;
5044 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005045 // AUDIO_SOURCE_HOTWORD is for internal use only:
5046 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005047 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
5048 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005049 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5050 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005051 patch.num_sinks = 1;
5052 //only one input device for now
5053 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005054 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005055 ssize_t index;
5056 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5057 index = mAudioPatches.indexOfKey(*patchHandle);
5058 } else {
5059 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5060 }
5061 sp< AudioPatch> patchDesc;
5062 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5063 if (index >= 0) {
5064 patchDesc = mAudioPatches.valueAt(index);
5065 afPatchHandle = patchDesc->mAfPatchHandle;
5066 }
5067
Eric Laurent1c333e22014-05-20 10:48:17 -07005068 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005069 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005070 0);
5071 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005072 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005073 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005074 if (index < 0) {
5075 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
5076 &patch, mUidCached);
5077 addAudioPatch(patchDesc->mHandle, patchDesc);
5078 } else {
5079 patchDesc->mPatch = patch;
5080 }
5081 patchDesc->mAfPatchHandle = afPatchHandle;
5082 patchDesc->mUid = mUidCached;
5083 if (patchHandle) {
5084 *patchHandle = patchDesc->mHandle;
5085 }
5086 inputDesc->mPatchHandle = patchDesc->mHandle;
5087 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005088 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005089 }
5090 }
5091 }
5092 return status;
5093}
5094
Eric Laurent6a94d692014-05-20 11:18:06 -07005095status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5096 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005097{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005098 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005099 ssize_t index;
5100 if (patchHandle) {
5101 index = mAudioPatches.indexOfKey(*patchHandle);
5102 } else {
5103 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5104 }
5105 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005106 return INVALID_OPERATION;
5107 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005108 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5109 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005110 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
5111 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005112 removeAudioPatch(patchDesc->mHandle);
5113 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005114 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005115 return status;
5116}
5117
5118sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08005119 String8 address,
Glenn Kastencbd48022014-07-24 13:46:44 -07005120 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07005121 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005122 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07005123 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005124{
5125 // Choose an input profile based on the requested capture parameters: select the first available
5126 // profile supporting all requested parameters.
5127
5128 for (size_t i = 0; i < mHwModules.size(); i++)
5129 {
5130 if (mHwModules[i]->mHandle == 0) {
5131 continue;
5132 }
5133 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5134 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005135 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005136 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005137 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005138 &samplingRate /*updatedSamplingRate*/,
5139 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005140
Eric Laurente552edb2014-03-10 17:42:56 -07005141 return profile;
5142 }
5143 }
5144 }
5145 return NULL;
5146}
5147
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005148
5149audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
Eric Laurentc722f302014-12-10 11:21:49 -08005150 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005151{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005152 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5153 ~AUDIO_DEVICE_BIT_IN;
Eric Laurent275e8e92014-11-30 15:14:47 -08005154
5155 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
5156 if (mPolicyMixes[i]->mMix.mMixType != MIX_TYPE_RECORDERS) {
5157 continue;
5158 }
5159 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
5160 if ((RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5161 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource == inputSource) ||
5162 (RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5163 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource != inputSource)) {
5164 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurentc722f302014-12-10 11:21:49 -08005165 if (policyMix != NULL) {
5166 *policyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005167 }
5168 return AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5169 }
5170 break;
5171 }
5172 }
5173 }
5174
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005175 return getDeviceForInputSource(inputSource);
5176}
5177
5178audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5179{
5180 uint32_t device = AUDIO_DEVICE_NONE;
5181 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5182 ~AUDIO_DEVICE_BIT_IN;
5183
Eric Laurente552edb2014-03-10 17:42:56 -07005184 switch (inputSource) {
5185 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005186 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005187 device = AUDIO_DEVICE_IN_VOICE_CALL;
5188 break;
5189 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005190 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005191
5192 case AUDIO_SOURCE_DEFAULT:
5193 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07005194 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
5195 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentdc136ff2014-12-16 12:24:18 -08005196 } else if ((mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO) &&
5197 (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET)) {
5198 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurentc2730ba2014-07-20 15:47:07 -07005199 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5200 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5201 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5202 device = AUDIO_DEVICE_IN_USB_DEVICE;
5203 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5204 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005205 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005206 break;
5207
5208 case AUDIO_SOURCE_VOICE_COMMUNICATION:
5209 // Allow only use of devices on primary input if in call and HAL does not support routing
5210 // to voice call path.
5211 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
5212 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
5213 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
5214 }
5215
5216 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
5217 case AUDIO_POLICY_FORCE_BT_SCO:
5218 // if SCO device is requested but no SCO device is available, fall back to default case
5219 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
5220 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
5221 break;
5222 }
5223 // FALL THROUGH
5224
5225 default: // FORCE_NONE
5226 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5227 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5228 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5229 device = AUDIO_DEVICE_IN_USB_DEVICE;
5230 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5231 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5232 }
5233 break;
5234
5235 case AUDIO_POLICY_FORCE_SPEAKER:
5236 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
5237 device = AUDIO_DEVICE_IN_BACK_MIC;
5238 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5239 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5240 }
5241 break;
5242 }
5243 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005244
Eric Laurente552edb2014-03-10 17:42:56 -07005245 case AUDIO_SOURCE_VOICE_RECOGNITION:
5246 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07005247 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005248 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005249 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005250 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005251 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07005252 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5253 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005254 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005255 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5256 }
5257 break;
5258 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005259 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005260 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005261 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005262 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5263 }
5264 break;
5265 case AUDIO_SOURCE_VOICE_DOWNLINK:
5266 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005267 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005268 device = AUDIO_DEVICE_IN_VOICE_CALL;
5269 }
5270 break;
5271 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005272 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07005273 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5274 }
5275 break;
Hochi Huang327cb702014-09-21 09:47:31 +08005276 case AUDIO_SOURCE_FM_TUNER:
5277 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
5278 device = AUDIO_DEVICE_IN_FM_TUNER;
5279 }
5280 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005281 default:
5282 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
5283 break;
5284 }
5285 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
5286 return device;
5287}
5288
Eric Laurente0720872014-03-11 09:30:41 -07005289bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005290{
5291 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
5292 device &= ~AUDIO_DEVICE_BIT_IN;
5293 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
5294 return true;
5295 }
5296 return false;
5297}
5298
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005299bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005300 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL & ~AUDIO_DEVICE_BIT_IN) != 0);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005301}
5302
Eric Laurente0720872014-03-11 09:30:41 -07005303audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005304{
5305 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005306 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07005307 if ((input_descriptor->mRefCount > 0)
5308 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
5309 return mInputs.keyAt(i);
5310 }
5311 }
5312 return 0;
5313}
5314
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005315uint32_t AudioPolicyManager::activeInputsCount() const
5316{
5317 uint32_t count = 0;
5318 for (size_t i = 0; i < mInputs.size(); i++) {
5319 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
5320 if (desc->mRefCount > 0) {
Eric Laurenta34c9ce2014-12-19 11:16:32 -08005321 count++;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005322 }
5323 }
5324 return count;
5325}
5326
Eric Laurente552edb2014-03-10 17:42:56 -07005327
Eric Laurente0720872014-03-11 09:30:41 -07005328audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005329{
5330 if (device == AUDIO_DEVICE_NONE) {
5331 // this happens when forcing a route update and no track is active on an output.
5332 // In this case the returned category is not important.
5333 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07005334 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07005335 // Multiple device selection is either:
5336 // - speaker + one other device: give priority to speaker in this case.
5337 // - one A2DP device + another device: happens with duplicated output. In this case
5338 // retain the device on the A2DP output as the other must not correspond to an active
5339 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09005340 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07005341 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
5342 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09005343 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
5344 device = AUDIO_DEVICE_OUT_HDMI_ARC;
5345 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
5346 device = AUDIO_DEVICE_OUT_AUX_LINE;
5347 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
5348 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07005349 } else {
5350 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
5351 }
5352 }
5353
Jon Eklund11c9fb12014-06-23 14:47:03 -05005354 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
5355 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
5356 device = AUDIO_DEVICE_OUT_SPEAKER;
5357
Eric Laurent3b73df72014-03-11 09:06:29 -07005358 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07005359 "getDeviceForVolume() invalid device combination: %08x",
5360 device);
5361
5362 return device;
5363}
5364
Eric Laurente0720872014-03-11 09:30:41 -07005365AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005366{
5367 switch(getDeviceForVolume(device)) {
5368 case AUDIO_DEVICE_OUT_EARPIECE:
5369 return DEVICE_CATEGORY_EARPIECE;
5370 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5371 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5372 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5373 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5374 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5375 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5376 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05005377 case AUDIO_DEVICE_OUT_LINE:
5378 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5379 /*USB? Remote submix?*/
5380 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07005381 case AUDIO_DEVICE_OUT_SPEAKER:
5382 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5383 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005384 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5385 case AUDIO_DEVICE_OUT_USB_DEVICE:
5386 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5387 default:
5388 return DEVICE_CATEGORY_SPEAKER;
5389 }
5390}
5391
Eric Laurent223fd5c2014-11-11 13:43:36 -08005392/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005393float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005394 int indexInUi)
5395{
5396 device_category deviceCategory = getDeviceCategory(device);
5397 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5398
5399 // the volume index in the UI is relative to the min and max volume indices for this stream type
5400 int nbSteps = 1 + curve[VOLMAX].mIndex -
5401 curve[VOLMIN].mIndex;
5402 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5403 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5404
5405 // find what part of the curve this index volume belongs to, or if it's out of bounds
5406 int segment = 0;
5407 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5408 return 0.0f;
5409 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5410 segment = 0;
5411 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5412 segment = 1;
5413 } else if (volIdx <= curve[VOLMAX].mIndex) {
5414 segment = 2;
5415 } else { // out of bounds
5416 return 1.0f;
5417 }
5418
5419 // linear interpolation in the attenuation table in dB
5420 float decibels = curve[segment].mDBAttenuation +
5421 ((float)(volIdx - curve[segment].mIndex)) *
5422 ( (curve[segment+1].mDBAttenuation -
5423 curve[segment].mDBAttenuation) /
5424 ((float)(curve[segment+1].mIndex -
5425 curve[segment].mIndex)) );
5426
5427 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5428
5429 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5430 curve[segment].mIndex, volIdx,
5431 curve[segment+1].mIndex,
5432 curve[segment].mDBAttenuation,
5433 decibels,
5434 curve[segment+1].mDBAttenuation,
5435 amplification);
5436
5437 return amplification;
5438}
5439
Eric Laurente0720872014-03-11 09:30:41 -07005440const AudioPolicyManager::VolumeCurvePoint
5441 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005442 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5443};
5444
Eric Laurente0720872014-03-11 09:30:41 -07005445const AudioPolicyManager::VolumeCurvePoint
5446 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005447 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5448};
5449
Eric Laurente0720872014-03-11 09:30:41 -07005450const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005451 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5452 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5453};
5454
5455const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005456 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005457 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5458};
5459
Eric Laurente0720872014-03-11 09:30:41 -07005460const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005461 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005462 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005463};
5464
5465const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005466 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005467 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5468};
5469
Eric Laurente0720872014-03-11 09:30:41 -07005470const AudioPolicyManager::VolumeCurvePoint
5471 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005472 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5473};
5474
5475// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5476// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5477// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5478// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5479
Eric Laurente0720872014-03-11 09:30:41 -07005480const AudioPolicyManager::VolumeCurvePoint
5481 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005482 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5483};
5484
Eric Laurente0720872014-03-11 09:30:41 -07005485const AudioPolicyManager::VolumeCurvePoint
5486 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005487 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5488};
5489
Eric Laurente0720872014-03-11 09:30:41 -07005490const AudioPolicyManager::VolumeCurvePoint
5491 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005492 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5493};
5494
Eric Laurente0720872014-03-11 09:30:41 -07005495const AudioPolicyManager::VolumeCurvePoint
5496 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005497 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5498};
5499
Eric Laurente0720872014-03-11 09:30:41 -07005500const AudioPolicyManager::VolumeCurvePoint
5501 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005502 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5503};
5504
Eric Laurente0720872014-03-11 09:30:41 -07005505const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005506 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5507 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5508};
5509
5510const AudioPolicyManager::VolumeCurvePoint
5511 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5512 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5513};
5514
5515const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005516 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5517 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5518};
5519
5520const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005521 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5522 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005523 { // AUDIO_STREAM_VOICE_CALL
5524 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5525 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005526 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5527 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005528 },
5529 { // AUDIO_STREAM_SYSTEM
5530 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5531 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005532 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5533 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005534 },
5535 { // AUDIO_STREAM_RING
5536 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5537 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005538 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5539 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005540 },
5541 { // AUDIO_STREAM_MUSIC
5542 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5543 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005544 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5545 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005546 },
5547 { // AUDIO_STREAM_ALARM
5548 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5549 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005550 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5551 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005552 },
5553 { // AUDIO_STREAM_NOTIFICATION
5554 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5555 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005556 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5557 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005558 },
5559 { // AUDIO_STREAM_BLUETOOTH_SCO
5560 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5561 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005562 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5563 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005564 },
5565 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5566 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5567 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005568 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5569 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005570 },
5571 { // AUDIO_STREAM_DTMF
5572 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5573 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005574 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5575 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005576 },
5577 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005578 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5579 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5580 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5581 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5582 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005583 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005584 { // AUDIO_STREAM_ACCESSIBILITY
5585 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5586 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5587 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5588 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5589 },
5590 { // AUDIO_STREAM_REROUTING
5591 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5592 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5593 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5594 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5595 },
5596 { // AUDIO_STREAM_PATCH
5597 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5598 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5599 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5600 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5601 },
Eric Laurente552edb2014-03-10 17:42:56 -07005602};
5603
Eric Laurente0720872014-03-11 09:30:41 -07005604void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005605{
5606 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5607 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5608 mStreams[i].mVolumeCurve[j] =
5609 sVolumeProfiles[i][j];
5610 }
5611 }
5612
5613 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5614 if (mSpeakerDrcEnabled) {
5615 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5616 sDefaultSystemVolumeCurveDrc;
5617 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5618 sSpeakerSonificationVolumeCurveDrc;
5619 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5620 sSpeakerSonificationVolumeCurveDrc;
5621 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5622 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005623 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5624 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005625 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5626 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005627 }
5628}
5629
Eric Laurente0720872014-03-11 09:30:41 -07005630float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005631 int index,
5632 audio_io_handle_t output,
5633 audio_devices_t device)
5634{
5635 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005636 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005637 StreamDescriptor &streamDesc = mStreams[stream];
5638
5639 if (device == AUDIO_DEVICE_NONE) {
5640 device = outputDesc->device();
5641 }
5642
Eric Laurente552edb2014-03-10 17:42:56 -07005643 volume = volIndexToAmpl(device, streamDesc, index);
5644
5645 // if a headset is connected, apply the following rules to ring tones and notifications
5646 // to avoid sound level bursts in user's ears:
5647 // - always attenuate ring tones and notifications volume by 6dB
5648 // - if music is playing, always limit the volume to current music volume,
5649 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005650 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005651 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5652 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5653 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5654 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5655 ((stream_strategy == STRATEGY_SONIFICATION)
5656 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005657 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005658 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005659 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005660 streamDesc.mCanBeMuted) {
5661 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5662 // when the phone is ringing we must consider that music could have been paused just before
5663 // by the music application and behave as if music was active if the last music track was
5664 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005665 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005666 mLimitRingtoneVolume) {
5667 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005668 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5669 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005670 output,
5671 musicDevice);
5672 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5673 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5674 if (volume > minVol) {
5675 volume = minVol;
5676 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5677 }
5678 }
5679 }
5680
5681 return volume;
5682}
5683
Eric Laurente0720872014-03-11 09:30:41 -07005684status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005685 int index,
5686 audio_io_handle_t output,
5687 audio_devices_t device,
5688 int delayMs,
5689 bool force)
5690{
5691
5692 // do not change actual stream volume if the stream is muted
5693 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5694 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5695 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5696 return NO_ERROR;
5697 }
5698
5699 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005700 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5701 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5702 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5703 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005704 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005705 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005706 return INVALID_OPERATION;
5707 }
5708
5709 float volume = computeVolume(stream, index, output, device);
Eric Laurent275e8e92014-11-30 15:14:47 -08005710 // unit gain if rerouting to external policy
5711 if (device == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
5712 ssize_t index = mOutputs.indexOfKey(output);
5713 if (index >= 0) {
5714 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurentc722f302014-12-10 11:21:49 -08005715 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005716 ALOGV("max gain when rerouting for output=%d", output);
5717 volume = 1.0f;
5718 }
5719 }
5720
5721 }
Eric Laurente552edb2014-03-10 17:42:56 -07005722 // We actually change the volume if:
5723 // - the float value returned by computeVolume() changed
5724 // - the force flag is set
5725 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5726 force) {
5727 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5728 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5729 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5730 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005731 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5732 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005733 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005734 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005735 }
5736
Eric Laurent3b73df72014-03-11 09:06:29 -07005737 if (stream == AUDIO_STREAM_VOICE_CALL ||
5738 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005739 float voiceVolume;
5740 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005741 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005742 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5743 } else {
5744 voiceVolume = 1.0;
5745 }
5746
5747 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5748 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5749 mLastVoiceVolume = voiceVolume;
5750 }
5751 }
5752
5753 return NO_ERROR;
5754}
5755
Eric Laurente0720872014-03-11 09:30:41 -07005756void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005757 audio_devices_t device,
5758 int delayMs,
5759 bool force)
5760{
5761 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5762
Eric Laurent3b73df72014-03-11 09:06:29 -07005763 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005764 if (stream == AUDIO_STREAM_PATCH) {
5765 continue;
5766 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005767 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005768 mStreams[stream].getVolumeIndex(device),
5769 output,
5770 device,
5771 delayMs,
5772 force);
5773 }
5774}
5775
Eric Laurente0720872014-03-11 09:30:41 -07005776void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005777 bool on,
5778 audio_io_handle_t output,
5779 int delayMs,
5780 audio_devices_t device)
5781{
5782 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005783 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005784 if (stream == AUDIO_STREAM_PATCH) {
5785 continue;
5786 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005787 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5788 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005789 }
5790 }
5791}
5792
Eric Laurente0720872014-03-11 09:30:41 -07005793void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005794 bool on,
5795 audio_io_handle_t output,
5796 int delayMs,
5797 audio_devices_t device)
5798{
5799 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005800 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005801 if (device == AUDIO_DEVICE_NONE) {
5802 device = outputDesc->device();
5803 }
5804
5805 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5806 stream, on, output, outputDesc->mMuteCount[stream], device);
5807
5808 if (on) {
5809 if (outputDesc->mMuteCount[stream] == 0) {
5810 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005811 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5812 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005813 checkAndSetVolume(stream, 0, output, device, delayMs);
5814 }
5815 }
5816 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5817 outputDesc->mMuteCount[stream]++;
5818 } else {
5819 if (outputDesc->mMuteCount[stream] == 0) {
5820 ALOGV("setStreamMute() unmuting non muted stream!");
5821 return;
5822 }
5823 if (--outputDesc->mMuteCount[stream] == 0) {
5824 checkAndSetVolume(stream,
5825 streamDesc.getVolumeIndex(device),
5826 output,
5827 device,
5828 delayMs);
5829 }
5830 }
5831}
5832
Eric Laurente0720872014-03-11 09:30:41 -07005833void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005834 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005835{
5836 // if the stream pertains to sonification strategy and we are in call we must
5837 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5838 // in the device used for phone strategy and play the tone if the selected device does not
5839 // interfere with the device used for phone strategy
5840 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5841 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005842 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005843 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5844 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005845 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005846 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5847 stream, starting, outputDesc->mDevice, stateChange);
5848 if (outputDesc->mRefCount[stream]) {
5849 int muteCount = 1;
5850 if (stateChange) {
5851 muteCount = outputDesc->mRefCount[stream];
5852 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005853 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005854 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5855 for (int i = 0; i < muteCount; i++) {
5856 setStreamMute(stream, starting, mPrimaryOutput);
5857 }
5858 } else {
5859 ALOGV("handleIncallSonification() high visibility");
5860 if (outputDesc->device() &
5861 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5862 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5863 for (int i = 0; i < muteCount; i++) {
5864 setStreamMute(stream, starting, mPrimaryOutput);
5865 }
5866 }
5867 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005868 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5869 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005870 } else {
5871 mpClientInterface->stopTone();
5872 }
5873 }
5874 }
5875 }
5876}
5877
Eric Laurente0720872014-03-11 09:30:41 -07005878bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005879{
5880 return isStateInCall(mPhoneState);
5881}
5882
Eric Laurente0720872014-03-11 09:30:41 -07005883bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005884 return ((state == AUDIO_MODE_IN_CALL) ||
5885 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005886}
5887
Eric Laurente0720872014-03-11 09:30:41 -07005888uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005889{
5890 return MAX_EFFECTS_CPU_LOAD;
5891}
5892
Eric Laurente0720872014-03-11 09:30:41 -07005893uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005894{
5895 return MAX_EFFECTS_MEMORY;
5896}
5897
Eric Laurent6a94d692014-05-20 11:18:06 -07005898
Eric Laurente552edb2014-03-10 17:42:56 -07005899// --- AudioOutputDescriptor class implementation
5900
Eric Laurente0720872014-03-11 09:30:41 -07005901AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005902 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005903 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurentc722f302014-12-10 11:21:49 -08005904 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL),
Eric Laurent275e8e92014-11-30 15:14:47 -08005905 mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005906 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5907{
5908 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005909 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005910 mRefCount[i] = 0;
5911 mCurVolume[i] = -1.0;
5912 mMuteCount[i] = 0;
5913 mStopTime[i] = 0;
5914 }
5915 for (int i = 0; i < NUM_STRATEGIES; i++) {
5916 mStrategyMutedByDevice[i] = false;
5917 }
5918 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005919 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005920 mSamplingRate = profile->pickSamplingRate();
5921 mFormat = profile->pickFormat();
5922 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005923 if (profile->mGains.size() > 0) {
5924 profile->mGains[0]->getDefaultConfig(&mGain);
5925 }
Eric Laurente552edb2014-03-10 17:42:56 -07005926 }
5927}
5928
Eric Laurente0720872014-03-11 09:30:41 -07005929audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005930{
5931 if (isDuplicated()) {
5932 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5933 } else {
5934 return mDevice;
5935 }
5936}
5937
Eric Laurente0720872014-03-11 09:30:41 -07005938uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005939{
5940 if (isDuplicated()) {
5941 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5942 } else {
5943 return mLatency;
5944 }
5945}
5946
Eric Laurente0720872014-03-11 09:30:41 -07005947bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005948 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005949{
5950 if (isDuplicated()) {
5951 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5952 } else if (outputDesc->isDuplicated()){
5953 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5954 } else {
5955 return (mProfile->mModule == outputDesc->mProfile->mModule);
5956 }
5957}
5958
Eric Laurente0720872014-03-11 09:30:41 -07005959void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005960 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005961{
5962 // forward usage count change to attached outputs
5963 if (isDuplicated()) {
5964 mOutput1->changeRefCount(stream, delta);
5965 mOutput2->changeRefCount(stream, delta);
5966 }
5967 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005968 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5969 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005970 mRefCount[stream] = 0;
5971 return;
5972 }
5973 mRefCount[stream] += delta;
5974 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5975}
5976
Eric Laurente0720872014-03-11 09:30:41 -07005977audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005978{
5979 if (isDuplicated()) {
5980 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5981 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005982 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005983 }
5984}
5985
Eric Laurente0720872014-03-11 09:30:41 -07005986bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005987{
5988 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5989}
5990
Eric Laurente0720872014-03-11 09:30:41 -07005991bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005992 uint32_t inPastMs,
5993 nsecs_t sysTime) const
5994{
5995 if ((sysTime == 0) && (inPastMs != 0)) {
5996 sysTime = systemTime();
5997 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005998 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005999 if (i == AUDIO_STREAM_PATCH) {
6000 continue;
6001 }
Eric Laurent3b73df72014-03-11 09:06:29 -07006002 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006003 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07006004 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006005 return true;
6006 }
6007 }
6008 return false;
6009}
6010
Eric Laurente0720872014-03-11 09:30:41 -07006011bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07006012 uint32_t inPastMs,
6013 nsecs_t sysTime) const
6014{
6015 if (mRefCount[stream] != 0) {
6016 return true;
6017 }
6018 if (inPastMs == 0) {
6019 return false;
6020 }
6021 if (sysTime == 0) {
6022 sysTime = systemTime();
6023 }
6024 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
6025 return true;
6026 }
6027 return false;
6028}
6029
Eric Laurent1c333e22014-05-20 10:48:17 -07006030void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006031 struct audio_port_config *dstConfig,
6032 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006033{
Eric Laurent84c70242014-06-23 08:46:27 -07006034 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
6035
Eric Laurent1f2f2232014-06-02 12:01:23 -07006036 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6037 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6038 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006039 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006040 }
6041 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6042
Eric Laurent6a94d692014-05-20 11:18:06 -07006043 dstConfig->id = mId;
6044 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
6045 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07006046 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6047 dstConfig->ext.mix.handle = mIoHandle;
6048 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07006049}
6050
6051void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
6052 struct audio_port *port) const
6053{
Eric Laurent84c70242014-06-23 08:46:27 -07006054 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07006055 mProfile->toAudioPort(port);
6056 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006057 toAudioPortConfig(&port->active_config);
6058 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006059 port->ext.mix.handle = mIoHandle;
6060 port->ext.mix.latency_class =
6061 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
6062}
Eric Laurente552edb2014-03-10 17:42:56 -07006063
Eric Laurente0720872014-03-11 09:30:41 -07006064status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006065{
6066 const size_t SIZE = 256;
6067 char buffer[SIZE];
6068 String8 result;
6069
Eric Laurent4d416952014-08-10 14:07:09 -07006070 snprintf(buffer, SIZE, " ID: %d\n", mId);
6071 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006072 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6073 result.append(buffer);
6074 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
6075 result.append(buffer);
6076 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6077 result.append(buffer);
6078 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
6079 result.append(buffer);
6080 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
6081 result.append(buffer);
6082 snprintf(buffer, SIZE, " Devices %08x\n", device());
6083 result.append(buffer);
6084 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
6085 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07006086 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
6087 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
6088 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07006089 result.append(buffer);
6090 }
6091 write(fd, result.string(), result.size());
6092
6093 return NO_ERROR;
6094}
6095
6096// --- AudioInputDescriptor class implementation
6097
Eric Laurent1c333e22014-05-20 10:48:17 -07006098AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006099 : mId(0), mIoHandle(0),
Eric Laurentc722f302014-12-10 11:21:49 -08006100 mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006101 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07006102{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006103 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006104 mSamplingRate = profile->pickSamplingRate();
6105 mFormat = profile->pickFormat();
6106 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07006107 if (profile->mGains.size() > 0) {
6108 profile->mGains[0]->getDefaultConfig(&mGain);
6109 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006110 }
Eric Laurente552edb2014-03-10 17:42:56 -07006111}
6112
Eric Laurent1c333e22014-05-20 10:48:17 -07006113void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006114 struct audio_port_config *dstConfig,
6115 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006116{
Eric Laurent84c70242014-06-23 08:46:27 -07006117 ALOG_ASSERT(mProfile != 0,
6118 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07006119 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6120 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6121 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006122 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006123 }
6124
6125 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6126
Eric Laurent6a94d692014-05-20 11:18:06 -07006127 dstConfig->id = mId;
6128 dstConfig->role = AUDIO_PORT_ROLE_SINK;
6129 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07006130 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6131 dstConfig->ext.mix.handle = mIoHandle;
6132 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07006133}
6134
6135void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
6136 struct audio_port *port) const
6137{
Eric Laurent84c70242014-06-23 08:46:27 -07006138 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
6139
Eric Laurent1c333e22014-05-20 10:48:17 -07006140 mProfile->toAudioPort(port);
6141 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006142 toAudioPortConfig(&port->active_config);
6143 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006144 port->ext.mix.handle = mIoHandle;
6145 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
6146}
6147
Eric Laurente0720872014-03-11 09:30:41 -07006148status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006149{
6150 const size_t SIZE = 256;
6151 char buffer[SIZE];
6152 String8 result;
6153
Eric Laurent4d416952014-08-10 14:07:09 -07006154 snprintf(buffer, SIZE, " ID: %d\n", mId);
6155 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006156 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6157 result.append(buffer);
6158 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
6159 result.append(buffer);
6160 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6161 result.append(buffer);
6162 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
6163 result.append(buffer);
6164 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
6165 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07006166 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
6167 result.append(buffer);
6168
Eric Laurente552edb2014-03-10 17:42:56 -07006169 write(fd, result.string(), result.size());
6170
6171 return NO_ERROR;
6172}
6173
6174// --- StreamDescriptor class implementation
6175
Eric Laurente0720872014-03-11 09:30:41 -07006176AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07006177 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
6178{
6179 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
6180}
6181
Eric Laurente0720872014-03-11 09:30:41 -07006182int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07006183{
Eric Laurente0720872014-03-11 09:30:41 -07006184 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07006185 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
6186 if (mIndexCur.indexOfKey(device) < 0) {
6187 device = AUDIO_DEVICE_OUT_DEFAULT;
6188 }
6189 return mIndexCur.valueFor(device);
6190}
6191
Eric Laurente0720872014-03-11 09:30:41 -07006192void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006193{
6194 const size_t SIZE = 256;
6195 char buffer[SIZE];
6196 String8 result;
6197
6198 snprintf(buffer, SIZE, "%s %02d %02d ",
6199 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
6200 result.append(buffer);
6201 for (size_t i = 0; i < mIndexCur.size(); i++) {
6202 snprintf(buffer, SIZE, "%04x : %02d, ",
6203 mIndexCur.keyAt(i),
6204 mIndexCur.valueAt(i));
6205 result.append(buffer);
6206 }
6207 result.append("\n");
6208
6209 write(fd, result.string(), result.size());
6210}
6211
6212// --- EffectDescriptor class implementation
6213
Eric Laurente0720872014-03-11 09:30:41 -07006214status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006215{
6216 const size_t SIZE = 256;
6217 char buffer[SIZE];
6218 String8 result;
6219
6220 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
6221 result.append(buffer);
6222 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
6223 result.append(buffer);
6224 snprintf(buffer, SIZE, " Session: %d\n", mSession);
6225 result.append(buffer);
6226 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
6227 result.append(buffer);
6228 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
6229 result.append(buffer);
6230 write(fd, result.string(), result.size());
6231
6232 return NO_ERROR;
6233}
6234
Eric Laurent1c333e22014-05-20 10:48:17 -07006235// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006236
Eric Laurente0720872014-03-11 09:30:41 -07006237AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07006238 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
6239 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07006240{
6241}
6242
Eric Laurente0720872014-03-11 09:30:41 -07006243AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07006244{
6245 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006246 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006247 }
6248 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006249 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006250 }
6251 free((void *)mName);
6252}
6253
Eric Laurent1afeecb2014-05-14 08:52:28 -07006254status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
6255{
6256 cnode *node = root->first_child;
6257
6258 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
6259
6260 while (node) {
6261 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6262 profile->loadSamplingRates((char *)node->value);
6263 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6264 profile->loadFormats((char *)node->value);
6265 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6266 profile->loadInChannels((char *)node->value);
6267 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6268 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6269 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07006270 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
6271 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006272 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6273 profile->loadGains(node);
6274 }
6275 node = node->next;
6276 }
6277 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6278 "loadInput() invalid supported devices");
6279 ALOGW_IF(profile->mChannelMasks.size() == 0,
6280 "loadInput() invalid supported channel masks");
6281 ALOGW_IF(profile->mSamplingRates.size() == 0,
6282 "loadInput() invalid supported sampling rates");
6283 ALOGW_IF(profile->mFormats.size() == 0,
6284 "loadInput() invalid supported formats");
6285 if (!profile->mSupportedDevices.isEmpty() &&
6286 (profile->mChannelMasks.size() != 0) &&
6287 (profile->mSamplingRates.size() != 0) &&
6288 (profile->mFormats.size() != 0)) {
6289
6290 ALOGV("loadInput() adding input Supported Devices %04x",
6291 profile->mSupportedDevices.types());
6292
6293 mInputProfiles.add(profile);
6294 return NO_ERROR;
6295 } else {
6296 return BAD_VALUE;
6297 }
6298}
6299
6300status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
6301{
6302 cnode *node = root->first_child;
6303
6304 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
6305
6306 while (node) {
6307 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6308 profile->loadSamplingRates((char *)node->value);
6309 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6310 profile->loadFormats((char *)node->value);
6311 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6312 profile->loadOutChannels((char *)node->value);
6313 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6314 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6315 mDeclaredDevices);
6316 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07006317 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006318 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6319 profile->loadGains(node);
6320 }
6321 node = node->next;
6322 }
6323 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6324 "loadOutput() invalid supported devices");
6325 ALOGW_IF(profile->mChannelMasks.size() == 0,
6326 "loadOutput() invalid supported channel masks");
6327 ALOGW_IF(profile->mSamplingRates.size() == 0,
6328 "loadOutput() invalid supported sampling rates");
6329 ALOGW_IF(profile->mFormats.size() == 0,
6330 "loadOutput() invalid supported formats");
6331 if (!profile->mSupportedDevices.isEmpty() &&
6332 (profile->mChannelMasks.size() != 0) &&
6333 (profile->mSamplingRates.size() != 0) &&
6334 (profile->mFormats.size() != 0)) {
6335
6336 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
6337 profile->mSupportedDevices.types(), profile->mFlags);
6338
6339 mOutputProfiles.add(profile);
6340 return NO_ERROR;
6341 } else {
6342 return BAD_VALUE;
6343 }
6344}
6345
6346status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
6347{
6348 cnode *node = root->first_child;
6349
6350 audio_devices_t type = AUDIO_DEVICE_NONE;
6351 while (node) {
6352 if (strcmp(node->name, DEVICE_TYPE) == 0) {
6353 type = parseDeviceNames((char *)node->value);
6354 break;
6355 }
6356 node = node->next;
6357 }
6358 if (type == AUDIO_DEVICE_NONE ||
6359 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
6360 ALOGW("loadDevice() bad type %08x", type);
6361 return BAD_VALUE;
6362 }
6363 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
6364 deviceDesc->mModule = this;
6365
6366 node = root->first_child;
6367 while (node) {
6368 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
6369 deviceDesc->mAddress = String8((char *)node->value);
6370 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6371 if (audio_is_input_device(type)) {
6372 deviceDesc->loadInChannels((char *)node->value);
6373 } else {
6374 deviceDesc->loadOutChannels((char *)node->value);
6375 }
6376 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6377 deviceDesc->loadGains(node);
6378 }
6379 node = node->next;
6380 }
6381
6382 ALOGV("loadDevice() adding device name %s type %08x address %s",
6383 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6384
6385 mDeclaredDevices.add(deviceDesc);
6386
6387 return NO_ERROR;
6388}
6389
Eric Laurent275e8e92014-11-30 15:14:47 -08006390status_t AudioPolicyManager::HwModule::addOutputProfile(String8 name, const audio_config_t *config,
6391 audio_devices_t device, String8 address)
6392{
6393 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SOURCE, this);
6394
6395 profile->mSamplingRates.add(config->sample_rate);
6396 profile->mChannelMasks.add(config->channel_mask);
6397 profile->mFormats.add(config->format);
6398
6399 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6400 devDesc->mAddress = address;
6401 profile->mSupportedDevices.add(devDesc);
6402
6403 mOutputProfiles.add(profile);
6404
6405 return NO_ERROR;
6406}
6407
6408status_t AudioPolicyManager::HwModule::removeOutputProfile(String8 name)
6409{
6410 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
6411 if (mOutputProfiles[i]->mName == name) {
6412 mOutputProfiles.removeAt(i);
6413 break;
6414 }
6415 }
6416
6417 return NO_ERROR;
6418}
6419
6420status_t AudioPolicyManager::HwModule::addInputProfile(String8 name, const audio_config_t *config,
6421 audio_devices_t device, String8 address)
6422{
6423 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SINK, this);
6424
6425 profile->mSamplingRates.add(config->sample_rate);
6426 profile->mChannelMasks.add(config->channel_mask);
6427 profile->mFormats.add(config->format);
6428
6429 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6430 devDesc->mAddress = address;
6431 profile->mSupportedDevices.add(devDesc);
6432
6433 ALOGV("addInputProfile() name %s rate %d mask 0x08", name.string(), config->sample_rate, config->channel_mask);
6434
6435 mInputProfiles.add(profile);
6436
6437 return NO_ERROR;
6438}
6439
6440status_t AudioPolicyManager::HwModule::removeInputProfile(String8 name)
6441{
6442 for (size_t i = 0; i < mInputProfiles.size(); i++) {
6443 if (mInputProfiles[i]->mName == name) {
6444 mInputProfiles.removeAt(i);
6445 break;
6446 }
6447 }
6448
6449 return NO_ERROR;
6450}
6451
6452
Eric Laurente0720872014-03-11 09:30:41 -07006453void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006454{
6455 const size_t SIZE = 256;
6456 char buffer[SIZE];
6457 String8 result;
6458
6459 snprintf(buffer, SIZE, " - name: %s\n", mName);
6460 result.append(buffer);
6461 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6462 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006463 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6464 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006465 write(fd, result.string(), result.size());
6466 if (mOutputProfiles.size()) {
6467 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6468 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006469 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006470 write(fd, buffer, strlen(buffer));
6471 mOutputProfiles[i]->dump(fd);
6472 }
6473 }
6474 if (mInputProfiles.size()) {
6475 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6476 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006477 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006478 write(fd, buffer, strlen(buffer));
6479 mInputProfiles[i]->dump(fd);
6480 }
6481 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006482 if (mDeclaredDevices.size()) {
6483 write(fd, " - devices:\n", strlen(" - devices:\n"));
6484 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6485 mDeclaredDevices[i]->dump(fd, 4, i);
6486 }
6487 }
Eric Laurente552edb2014-03-10 17:42:56 -07006488}
6489
Eric Laurent1c333e22014-05-20 10:48:17 -07006490// --- AudioPort class implementation
6491
Eric Laurenta121f902014-06-03 13:32:54 -07006492
6493AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6494 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07006495 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006496{
6497 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6498 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6499}
6500
Eric Laurent1c333e22014-05-20 10:48:17 -07006501void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6502{
6503 port->role = mRole;
6504 port->type = mType;
6505 unsigned int i;
6506 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006507 if (mSamplingRates[i] != 0) {
6508 port->sample_rates[i] = mSamplingRates[i];
6509 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006510 }
6511 port->num_sample_rates = i;
6512 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006513 if (mChannelMasks[i] != 0) {
6514 port->channel_masks[i] = mChannelMasks[i];
6515 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006516 }
6517 port->num_channel_masks = i;
6518 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006519 if (mFormats[i] != 0) {
6520 port->formats[i] = mFormats[i];
6521 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006522 }
6523 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006524
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006525 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006526
6527 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6528 port->gains[i] = mGains[i]->mGain;
6529 }
6530 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006531}
6532
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006533void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6534 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6535 const uint32_t rate = port->mSamplingRates.itemAt(k);
6536 if (rate != 0) { // skip "dynamic" rates
6537 bool hasRate = false;
6538 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6539 if (rate == mSamplingRates.itemAt(l)) {
6540 hasRate = true;
6541 break;
6542 }
6543 }
6544 if (!hasRate) { // never import a sampling rate twice
6545 mSamplingRates.add(rate);
6546 }
6547 }
6548 }
6549 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6550 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6551 if (mask != 0) { // skip "dynamic" masks
6552 bool hasMask = false;
6553 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6554 if (mask == mChannelMasks.itemAt(l)) {
6555 hasMask = true;
6556 break;
6557 }
6558 }
6559 if (!hasMask) { // never import a channel mask twice
6560 mChannelMasks.add(mask);
6561 }
6562 }
6563 }
6564 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6565 const audio_format_t format = port->mFormats.itemAt(k);
6566 if (format != 0) { // skip "dynamic" formats
6567 bool hasFormat = false;
6568 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6569 if (format == mFormats.itemAt(l)) {
6570 hasFormat = true;
6571 break;
6572 }
6573 }
6574 if (!hasFormat) { // never import a channel mask twice
6575 mFormats.add(format);
6576 }
6577 }
6578 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006579 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6580 sp<AudioGain> gain = port->mGains.itemAt(k);
6581 if (gain != 0) {
6582 bool hasGain = false;
6583 for (size_t l = 0 ; l < mGains.size() ; l++) {
6584 if (gain == mGains.itemAt(l)) {
6585 hasGain = true;
6586 break;
6587 }
6588 }
6589 if (!hasGain) { // never import a gain twice
6590 mGains.add(gain);
6591 }
6592 }
6593 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006594}
6595
6596void AudioPolicyManager::AudioPort::clearCapabilities() {
6597 mChannelMasks.clear();
6598 mFormats.clear();
6599 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006600 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006601}
Eric Laurent1c333e22014-05-20 10:48:17 -07006602
6603void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6604{
6605 char *str = strtok(name, "|");
6606
6607 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6608 // rates should be read from the output stream after it is opened for the first time
6609 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6610 mSamplingRates.add(0);
6611 return;
6612 }
6613
6614 while (str != NULL) {
6615 uint32_t rate = atoi(str);
6616 if (rate != 0) {
6617 ALOGV("loadSamplingRates() adding rate %d", rate);
6618 mSamplingRates.add(rate);
6619 }
6620 str = strtok(NULL, "|");
6621 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006622}
6623
6624void AudioPolicyManager::AudioPort::loadFormats(char *name)
6625{
6626 char *str = strtok(name, "|");
6627
6628 // by convention, "0' in the first entry in mFormats indicates the supported formats
6629 // should be read from the output stream after it is opened for the first time
6630 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6631 mFormats.add(AUDIO_FORMAT_DEFAULT);
6632 return;
6633 }
6634
6635 while (str != NULL) {
6636 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6637 ARRAY_SIZE(sFormatNameToEnumTable),
6638 str);
6639 if (format != AUDIO_FORMAT_DEFAULT) {
6640 mFormats.add(format);
6641 }
6642 str = strtok(NULL, "|");
6643 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006644}
6645
6646void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6647{
6648 const char *str = strtok(name, "|");
6649
6650 ALOGV("loadInChannels() %s", name);
6651
6652 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6653 mChannelMasks.add(0);
6654 return;
6655 }
6656
6657 while (str != NULL) {
6658 audio_channel_mask_t channelMask =
6659 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6660 ARRAY_SIZE(sInChannelsNameToEnumTable),
6661 str);
6662 if (channelMask != 0) {
6663 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6664 mChannelMasks.add(channelMask);
6665 }
6666 str = strtok(NULL, "|");
6667 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006668}
6669
6670void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6671{
6672 const char *str = strtok(name, "|");
6673
6674 ALOGV("loadOutChannels() %s", name);
6675
6676 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6677 // masks should be read from the output stream after it is opened for the first time
6678 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6679 mChannelMasks.add(0);
6680 return;
6681 }
6682
6683 while (str != NULL) {
6684 audio_channel_mask_t channelMask =
6685 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6686 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6687 str);
6688 if (channelMask != 0) {
6689 mChannelMasks.add(channelMask);
6690 }
6691 str = strtok(NULL, "|");
6692 }
6693 return;
6694}
6695
Eric Laurent1afeecb2014-05-14 08:52:28 -07006696audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6697{
6698 const char *str = strtok(name, "|");
6699
6700 ALOGV("loadGainMode() %s", name);
6701 audio_gain_mode_t mode = 0;
6702 while (str != NULL) {
6703 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6704 ARRAY_SIZE(sGainModeNameToEnumTable),
6705 str);
6706 str = strtok(NULL, "|");
6707 }
6708 return mode;
6709}
6710
Eric Laurenta121f902014-06-03 13:32:54 -07006711void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006712{
6713 cnode *node = root->first_child;
6714
Eric Laurenta121f902014-06-03 13:32:54 -07006715 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006716
6717 while (node) {
6718 if (strcmp(node->name, GAIN_MODE) == 0) {
6719 gain->mGain.mode = loadGainMode((char *)node->value);
6720 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006721 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006722 gain->mGain.channel_mask =
6723 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6724 ARRAY_SIZE(sInChannelsNameToEnumTable),
6725 (char *)node->value);
6726 } else {
6727 gain->mGain.channel_mask =
6728 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6729 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6730 (char *)node->value);
6731 }
6732 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6733 gain->mGain.min_value = atoi((char *)node->value);
6734 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6735 gain->mGain.max_value = atoi((char *)node->value);
6736 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6737 gain->mGain.default_value = atoi((char *)node->value);
6738 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6739 gain->mGain.step_value = atoi((char *)node->value);
6740 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6741 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6742 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6743 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6744 }
6745 node = node->next;
6746 }
6747
6748 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6749 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6750
6751 if (gain->mGain.mode == 0) {
6752 return;
6753 }
6754 mGains.add(gain);
6755}
6756
6757void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6758{
6759 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006760 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006761 while (node) {
6762 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006763 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006764 node = node->next;
6765 }
6766}
6767
Glenn Kastencbd48022014-07-24 13:46:44 -07006768status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006769{
Eric Laurent0daea392014-12-04 19:14:54 -08006770 if (mSamplingRates.isEmpty()) {
6771 return NO_ERROR;
6772 }
6773
Eric Laurenta121f902014-06-03 13:32:54 -07006774 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6775 if (mSamplingRates[i] == samplingRate) {
6776 return NO_ERROR;
6777 }
6778 }
6779 return BAD_VALUE;
6780}
6781
Glenn Kastencbd48022014-07-24 13:46:44 -07006782status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6783 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006784{
Eric Laurent0daea392014-12-04 19:14:54 -08006785 if (mSamplingRates.isEmpty()) {
6786 return NO_ERROR;
6787 }
6788
Glenn Kastencbd48022014-07-24 13:46:44 -07006789 // Search for the closest supported sampling rate that is above (preferred)
6790 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6791 // The sampling rates do not need to be sorted in ascending order.
6792 ssize_t maxBelow = -1;
6793 ssize_t minAbove = -1;
6794 uint32_t candidate;
6795 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6796 candidate = mSamplingRates[i];
6797 if (candidate == samplingRate) {
6798 if (updatedSamplingRate != NULL) {
6799 *updatedSamplingRate = candidate;
6800 }
6801 return NO_ERROR;
6802 }
6803 // candidate < desired
6804 if (candidate < samplingRate) {
6805 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6806 maxBelow = i;
6807 }
6808 // candidate > desired
6809 } else {
6810 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6811 minAbove = i;
6812 }
6813 }
6814 }
6815 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6816 // TODO Move these assumptions out.
6817 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6818 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6819 // due to approximation by an int32_t of the
6820 // phase increments
6821 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6822 if (minAbove >= 0) {
6823 candidate = mSamplingRates[minAbove];
6824 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6825 if (updatedSamplingRate != NULL) {
6826 *updatedSamplingRate = candidate;
6827 }
6828 return NO_ERROR;
6829 }
6830 }
6831 // But if we have to up-sample from a lower sampling rate, that's OK.
6832 if (maxBelow >= 0) {
6833 candidate = mSamplingRates[maxBelow];
6834 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6835 if (updatedSamplingRate != NULL) {
6836 *updatedSamplingRate = candidate;
6837 }
6838 return NO_ERROR;
6839 }
6840 }
6841 // leave updatedSamplingRate unmodified
6842 return BAD_VALUE;
6843}
6844
6845status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6846{
Eric Laurent0daea392014-12-04 19:14:54 -08006847 if (mChannelMasks.isEmpty()) {
6848 return NO_ERROR;
6849 }
6850
Glenn Kastencbd48022014-07-24 13:46:44 -07006851 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006852 if (mChannelMasks[i] == channelMask) {
6853 return NO_ERROR;
6854 }
6855 }
6856 return BAD_VALUE;
6857}
6858
Glenn Kastencbd48022014-07-24 13:46:44 -07006859status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6860 const
6861{
Eric Laurent0daea392014-12-04 19:14:54 -08006862 if (mChannelMasks.isEmpty()) {
6863 return NO_ERROR;
6864 }
6865
Glenn Kastencbd48022014-07-24 13:46:44 -07006866 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6867 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6868 // FIXME Does not handle multi-channel automatic conversions yet
6869 audio_channel_mask_t supported = mChannelMasks[i];
6870 if (supported == channelMask) {
6871 return NO_ERROR;
6872 }
6873 if (isRecordThread) {
6874 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6875 // FIXME Abstract this out to a table.
6876 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6877 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6878 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6879 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6880 return NO_ERROR;
6881 }
6882 }
6883 }
6884 return BAD_VALUE;
6885}
6886
Eric Laurenta121f902014-06-03 13:32:54 -07006887status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6888{
Eric Laurent0daea392014-12-04 19:14:54 -08006889 if (mFormats.isEmpty()) {
6890 return NO_ERROR;
6891 }
6892
Eric Laurenta121f902014-06-03 13:32:54 -07006893 for (size_t i = 0; i < mFormats.size(); i ++) {
6894 if (mFormats[i] == format) {
6895 return NO_ERROR;
6896 }
6897 }
6898 return BAD_VALUE;
6899}
6900
Eric Laurent1e693b52014-07-09 15:03:28 -07006901
6902uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6903{
6904 // special case for uninitialized dynamic profile
6905 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6906 return 0;
6907 }
6908
Eric Laurent828bcff2014-09-07 12:26:06 -07006909 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6910 // channel count / sampling rate combination chosen will be supported by the connected
6911 // sink
6912 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6913 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6914 uint32_t samplingRate = UINT_MAX;
6915 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6916 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6917 samplingRate = mSamplingRates[i];
6918 }
6919 }
6920 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6921 }
6922
Eric Laurent1e693b52014-07-09 15:03:28 -07006923 uint32_t samplingRate = 0;
6924 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6925
6926 // For mixed output and inputs, use max mixer sampling rates. Do not
6927 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006928 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006929 maxRate = UINT_MAX;
6930 }
6931 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6932 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6933 samplingRate = mSamplingRates[i];
6934 }
6935 }
6936 return samplingRate;
6937}
6938
6939audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6940{
6941 // special case for uninitialized dynamic profile
6942 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6943 return AUDIO_CHANNEL_NONE;
6944 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006945 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006946
6947 // For direct outputs, pick minimum channel count: this helps ensuring that the
6948 // channel count / sampling rate combination chosen will be supported by the connected
6949 // sink
6950 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6951 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6952 uint32_t channelCount = UINT_MAX;
6953 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6954 uint32_t cnlCount;
6955 if (mUseInChannelMask) {
6956 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6957 } else {
6958 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6959 }
6960 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6961 channelMask = mChannelMasks[i];
6962 channelCount = cnlCount;
6963 }
6964 }
6965 return channelMask;
6966 }
6967
Eric Laurent1e693b52014-07-09 15:03:28 -07006968 uint32_t channelCount = 0;
6969 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6970
6971 // For mixed output and inputs, use max mixer channel count. Do not
6972 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006973 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006974 maxCount = UINT_MAX;
6975 }
6976 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6977 uint32_t cnlCount;
6978 if (mUseInChannelMask) {
6979 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6980 } else {
6981 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6982 }
6983 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6984 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006985 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006986 }
6987 }
6988 return channelMask;
6989}
6990
Andy Hung9a605382014-07-28 16:16:31 -07006991/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006992const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6993 AUDIO_FORMAT_DEFAULT,
6994 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006995 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006996 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006997 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006998 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006999};
7000
7001int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
7002 audio_format_t format2)
7003{
7004 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
7005 // compressed format and better than any PCM format. This is by design of pickFormat()
7006 if (!audio_is_linear_pcm(format1)) {
7007 if (!audio_is_linear_pcm(format2)) {
7008 return 0;
7009 }
7010 return 1;
7011 }
7012 if (!audio_is_linear_pcm(format2)) {
7013 return -1;
7014 }
7015
7016 int index1 = -1, index2 = -1;
7017 for (size_t i = 0;
7018 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
7019 i ++) {
7020 if (sPcmFormatCompareTable[i] == format1) {
7021 index1 = i;
7022 }
7023 if (sPcmFormatCompareTable[i] == format2) {
7024 index2 = i;
7025 }
7026 }
7027 // format1 not found => index1 < 0 => format2 > format1
7028 // format2 not found => index2 < 0 => format2 < format1
7029 return index1 - index2;
7030}
7031
7032audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
7033{
7034 // special case for uninitialized dynamic profile
7035 if (mFormats.size() == 1 && mFormats[0] == 0) {
7036 return AUDIO_FORMAT_DEFAULT;
7037 }
7038
7039 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07007040 audio_format_t bestFormat =
7041 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
7042 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07007043 // For mixed output and inputs, use best mixer output format. Do not
7044 // limit format otherwise
7045 if ((mType != AUDIO_PORT_TYPE_MIX) ||
7046 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07007047 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007048 bestFormat = AUDIO_FORMAT_INVALID;
7049 }
7050
7051 for (size_t i = 0; i < mFormats.size(); i ++) {
7052 if ((compareFormats(mFormats[i], format) > 0) &&
7053 (compareFormats(mFormats[i], bestFormat) <= 0)) {
7054 format = mFormats[i];
7055 }
7056 }
7057 return format;
7058}
7059
Eric Laurenta121f902014-06-03 13:32:54 -07007060status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
7061 int index) const
7062{
7063 if (index < 0 || (size_t)index >= mGains.size()) {
7064 return BAD_VALUE;
7065 }
7066 return mGains[index]->checkConfig(gainConfig);
7067}
7068
Eric Laurent1afeecb2014-05-14 08:52:28 -07007069void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
7070{
7071 const size_t SIZE = 256;
7072 char buffer[SIZE];
7073 String8 result;
7074
7075 if (mName.size() != 0) {
7076 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
7077 result.append(buffer);
7078 }
7079
7080 if (mSamplingRates.size() != 0) {
7081 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
7082 result.append(buffer);
7083 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007084 if (i == 0 && mSamplingRates[i] == 0) {
7085 snprintf(buffer, SIZE, "Dynamic");
7086 } else {
7087 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
7088 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007089 result.append(buffer);
7090 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
7091 }
7092 result.append("\n");
7093 }
7094
7095 if (mChannelMasks.size() != 0) {
7096 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
7097 result.append(buffer);
7098 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007099 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
7100
7101 if (i == 0 && mChannelMasks[i] == 0) {
7102 snprintf(buffer, SIZE, "Dynamic");
7103 } else {
7104 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
7105 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007106 result.append(buffer);
7107 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
7108 }
7109 result.append("\n");
7110 }
7111
7112 if (mFormats.size() != 0) {
7113 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
7114 result.append(buffer);
7115 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007116 const char *formatStr = enumToString(sFormatNameToEnumTable,
7117 ARRAY_SIZE(sFormatNameToEnumTable),
7118 mFormats[i]);
7119 if (i == 0 && strcmp(formatStr, "") == 0) {
7120 snprintf(buffer, SIZE, "Dynamic");
7121 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07007122 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07007123 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007124 result.append(buffer);
7125 result.append(i == (mFormats.size() - 1) ? "" : ", ");
7126 }
7127 result.append("\n");
7128 }
7129 write(fd, result.string(), result.size());
7130 if (mGains.size() != 0) {
7131 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
7132 write(fd, buffer, strlen(buffer) + 1);
7133 result.append(buffer);
7134 for (size_t i = 0; i < mGains.size(); i++) {
7135 mGains[i]->dump(fd, spaces + 2, i);
7136 }
7137 }
7138}
7139
7140// --- AudioGain class implementation
7141
Eric Laurenta121f902014-06-03 13:32:54 -07007142AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07007143{
Eric Laurenta121f902014-06-03 13:32:54 -07007144 mIndex = index;
7145 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007146 memset(&mGain, 0, sizeof(struct audio_gain));
7147}
7148
Eric Laurenta121f902014-06-03 13:32:54 -07007149void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
7150{
7151 config->index = mIndex;
7152 config->mode = mGain.mode;
7153 config->channel_mask = mGain.channel_mask;
7154 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7155 config->values[0] = mGain.default_value;
7156 } else {
7157 uint32_t numValues;
7158 if (mUseInChannelMask) {
7159 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
7160 } else {
7161 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
7162 }
7163 for (size_t i = 0; i < numValues; i++) {
7164 config->values[i] = mGain.default_value;
7165 }
7166 }
7167 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7168 config->ramp_duration_ms = mGain.min_ramp_ms;
7169 }
7170}
7171
7172status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
7173{
7174 if ((config->mode & ~mGain.mode) != 0) {
7175 return BAD_VALUE;
7176 }
7177 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7178 if ((config->values[0] < mGain.min_value) ||
7179 (config->values[0] > mGain.max_value)) {
7180 return BAD_VALUE;
7181 }
7182 } else {
7183 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
7184 return BAD_VALUE;
7185 }
7186 uint32_t numValues;
7187 if (mUseInChannelMask) {
7188 numValues = audio_channel_count_from_in_mask(config->channel_mask);
7189 } else {
7190 numValues = audio_channel_count_from_out_mask(config->channel_mask);
7191 }
7192 for (size_t i = 0; i < numValues; i++) {
7193 if ((config->values[i] < mGain.min_value) ||
7194 (config->values[i] > mGain.max_value)) {
7195 return BAD_VALUE;
7196 }
7197 }
7198 }
7199 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7200 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
7201 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
7202 return BAD_VALUE;
7203 }
7204 }
7205 return NO_ERROR;
7206}
7207
Eric Laurent1afeecb2014-05-14 08:52:28 -07007208void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
7209{
7210 const size_t SIZE = 256;
7211 char buffer[SIZE];
7212 String8 result;
7213
7214 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
7215 result.append(buffer);
7216 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
7217 result.append(buffer);
7218 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
7219 result.append(buffer);
7220 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
7221 result.append(buffer);
7222 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
7223 result.append(buffer);
7224 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
7225 result.append(buffer);
7226 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
7227 result.append(buffer);
7228 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
7229 result.append(buffer);
7230 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
7231 result.append(buffer);
7232
7233 write(fd, result.string(), result.size());
7234}
7235
Eric Laurent1f2f2232014-06-02 12:01:23 -07007236// --- AudioPortConfig class implementation
7237
7238AudioPolicyManager::AudioPortConfig::AudioPortConfig()
7239{
7240 mSamplingRate = 0;
7241 mChannelMask = AUDIO_CHANNEL_NONE;
7242 mFormat = AUDIO_FORMAT_INVALID;
7243 mGain.index = -1;
7244}
7245
Eric Laurenta121f902014-06-03 13:32:54 -07007246status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
7247 const struct audio_port_config *config,
7248 struct audio_port_config *backupConfig)
7249{
7250 struct audio_port_config localBackupConfig;
7251 status_t status = NO_ERROR;
7252
7253 localBackupConfig.config_mask = config->config_mask;
7254 toAudioPortConfig(&localBackupConfig);
7255
Marco Nelissen961ec212014-08-25 15:58:39 -07007256 sp<AudioPort> audioport = getAudioPort();
7257 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07007258 status = NO_INIT;
7259 goto exit;
7260 }
7261 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007262 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07007263 if (status != NO_ERROR) {
7264 goto exit;
7265 }
7266 mSamplingRate = config->sample_rate;
7267 }
7268 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007269 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07007270 if (status != NO_ERROR) {
7271 goto exit;
7272 }
7273 mChannelMask = config->channel_mask;
7274 }
7275 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007276 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07007277 if (status != NO_ERROR) {
7278 goto exit;
7279 }
7280 mFormat = config->format;
7281 }
7282 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007283 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07007284 if (status != NO_ERROR) {
7285 goto exit;
7286 }
7287 mGain = config->gain;
7288 }
7289
7290exit:
7291 if (status != NO_ERROR) {
7292 applyAudioPortConfig(&localBackupConfig);
7293 }
7294 if (backupConfig != NULL) {
7295 *backupConfig = localBackupConfig;
7296 }
7297 return status;
7298}
7299
Eric Laurent1f2f2232014-06-02 12:01:23 -07007300void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
7301 struct audio_port_config *dstConfig,
7302 const struct audio_port_config *srcConfig) const
7303{
7304 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
7305 dstConfig->sample_rate = mSamplingRate;
7306 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
7307 dstConfig->sample_rate = srcConfig->sample_rate;
7308 }
7309 } else {
7310 dstConfig->sample_rate = 0;
7311 }
7312 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
7313 dstConfig->channel_mask = mChannelMask;
7314 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
7315 dstConfig->channel_mask = srcConfig->channel_mask;
7316 }
7317 } else {
7318 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
7319 }
7320 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
7321 dstConfig->format = mFormat;
7322 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
7323 dstConfig->format = srcConfig->format;
7324 }
7325 } else {
7326 dstConfig->format = AUDIO_FORMAT_INVALID;
7327 }
7328 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
7329 dstConfig->gain = mGain;
7330 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
7331 dstConfig->gain = srcConfig->gain;
7332 }
7333 } else {
7334 dstConfig->gain.index = -1;
7335 }
7336 if (dstConfig->gain.index != -1) {
7337 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
7338 } else {
7339 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
7340 }
7341}
7342
Eric Laurent1c333e22014-05-20 10:48:17 -07007343// --- IOProfile class implementation
7344
Eric Laurent1afeecb2014-05-14 08:52:28 -07007345AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07007346 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07007347 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07007348{
7349}
7350
Eric Laurente0720872014-03-11 09:30:41 -07007351AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07007352{
7353}
7354
7355// checks if the IO profile is compatible with specified parameters.
7356// Sampling rate, format and channel mask must be specified in order to
7357// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07007358bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08007359 String8 address,
7360 uint32_t samplingRate,
7361 uint32_t *updatedSamplingRate,
7362 audio_format_t format,
7363 audio_channel_mask_t channelMask,
7364 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07007365{
Glenn Kastencbd48022014-07-24 13:46:44 -07007366 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
7367 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
7368 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07007369
Eric Laurent275e8e92014-11-30 15:14:47 -08007370 if (device != AUDIO_DEVICE_NONE && mSupportedDevices.getDevice(device, address) == 0) {
Glenn Kastencbd48022014-07-24 13:46:44 -07007371 return false;
7372 }
7373
7374 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07007375 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007376 }
7377 uint32_t myUpdatedSamplingRate = samplingRate;
7378 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007379 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007380 }
7381 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
7382 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007383 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007384 }
7385
7386 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
7387 return false;
7388 }
7389
7390 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
7391 checkExactChannelMask(channelMask) != NO_ERROR)) {
7392 return false;
7393 }
7394 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
7395 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
7396 return false;
7397 }
7398
7399 if (isPlaybackThread && (mFlags & flags) != flags) {
7400 return false;
7401 }
7402 // The only input flag that is allowed to be different is the fast flag.
7403 // An existing fast stream is compatible with a normal track request.
7404 // An existing normal stream is compatible with a fast track request,
7405 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07007406 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07007407 ~AUDIO_INPUT_FLAG_FAST)) {
7408 return false;
7409 }
7410
7411 if (updatedSamplingRate != NULL) {
7412 *updatedSamplingRate = myUpdatedSamplingRate;
7413 }
7414 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07007415}
7416
Eric Laurente0720872014-03-11 09:30:41 -07007417void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07007418{
7419 const size_t SIZE = 256;
7420 char buffer[SIZE];
7421 String8 result;
7422
Eric Laurent1afeecb2014-05-14 08:52:28 -07007423 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007424
Eric Laurente552edb2014-03-10 17:42:56 -07007425 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
7426 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007427 snprintf(buffer, SIZE, " - devices:\n");
7428 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07007429 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07007430 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
7431 mSupportedDevices[i]->dump(fd, 6, i);
7432 }
Eric Laurente552edb2014-03-10 17:42:56 -07007433}
7434
Eric Laurentd4692962014-05-05 18:13:44 -07007435void AudioPolicyManager::IOProfile::log()
7436{
7437 const size_t SIZE = 256;
7438 char buffer[SIZE];
7439 String8 result;
7440
7441 ALOGV(" - sampling rates: ");
7442 for (size_t i = 0; i < mSamplingRates.size(); i++) {
7443 ALOGV(" %d", mSamplingRates[i]);
7444 }
7445
7446 ALOGV(" - channel masks: ");
7447 for (size_t i = 0; i < mChannelMasks.size(); i++) {
7448 ALOGV(" 0x%04x", mChannelMasks[i]);
7449 }
7450
7451 ALOGV(" - formats: ");
7452 for (size_t i = 0; i < mFormats.size(); i++) {
7453 ALOGV(" 0x%08x", mFormats[i]);
7454 }
7455
7456 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
7457 ALOGV(" - flags: 0x%04x\n", mFlags);
7458}
7459
7460
Eric Laurent3a4311c2014-03-17 12:00:47 -07007461// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07007462
Eric Laurent1f2f2232014-06-02 12:01:23 -07007463
7464AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
7465 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7466 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7467 AUDIO_PORT_ROLE_SOURCE,
7468 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07007469 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07007470{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007471}
7472
Eric Laurent3a4311c2014-03-17 12:00:47 -07007473bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07007474{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007475 // Devices are considered equal if they:
7476 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7477 // - have the same address or one device does not specify the address
7478 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007479 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007480 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007481 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007482 mChannelMask == other->mChannelMask);
7483}
7484
Eric Laurent1db89b92015-01-27 18:21:09 -08007485void AudioPolicyManager::DeviceDescriptor::loadGains(cnode *root)
7486{
7487 AudioPort::loadGains(root);
7488 if (mGains.size() > 0) {
7489 mGains[0]->getDefaultConfig(&mGain);
7490 }
7491}
7492
7493
Eric Laurent3a4311c2014-03-17 12:00:47 -07007494void AudioPolicyManager::DeviceVector::refreshTypes()
7495{
Eric Laurent1c333e22014-05-20 10:48:17 -07007496 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007497 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007498 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007499 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007500 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007501}
7502
7503ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7504{
7505 for(size_t i = 0; i < size(); i++) {
7506 if (item->equals(itemAt(i))) {
7507 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007508 }
7509 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007510 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007511}
7512
Eric Laurent3a4311c2014-03-17 12:00:47 -07007513ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007514{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007515 ssize_t ret = indexOf(item);
7516
7517 if (ret < 0) {
7518 ret = SortedVector::add(item);
7519 if (ret >= 0) {
7520 refreshTypes();
7521 }
7522 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007523 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007524 ret = -1;
7525 }
7526 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007527}
7528
Eric Laurent3a4311c2014-03-17 12:00:47 -07007529ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7530{
7531 size_t i;
7532 ssize_t ret = indexOf(item);
7533
7534 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007535 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007536 } else {
7537 ret = SortedVector::removeAt(ret);
7538 if (ret >= 0) {
7539 refreshTypes();
7540 }
7541 }
7542 return ret;
7543}
7544
7545void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7546{
7547 DeviceVector deviceList;
7548
7549 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7550 types &= ~role_bit;
7551
7552 while (types) {
7553 uint32_t i = 31 - __builtin_clz(types);
7554 uint32_t type = 1 << i;
7555 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007556 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007557 }
7558}
7559
Eric Laurent1afeecb2014-05-14 08:52:28 -07007560void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7561 const DeviceVector& declaredDevices)
7562{
7563 char *devName = strtok(name, "|");
7564 while (devName != NULL) {
7565 if (strlen(devName) != 0) {
7566 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7567 ARRAY_SIZE(sDeviceNameToEnumTable),
7568 devName);
7569 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007570 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
Eric Laurent275e8e92014-11-30 15:14:47 -08007571 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX ||
7572 type == AUDIO_DEVICE_OUT_REMOTE_SUBMIX ) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007573 dev->mAddress = String8("0");
7574 }
7575 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007576 } else {
7577 sp<DeviceDescriptor> deviceDesc =
7578 declaredDevices.getDeviceFromName(String8(devName));
7579 if (deviceDesc != 0) {
7580 add(deviceDesc);
7581 }
7582 }
7583 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007584 devName = strtok(NULL, "|");
Eric Laurent1afeecb2014-05-14 08:52:28 -07007585 }
7586}
7587
Eric Laurent1c333e22014-05-20 10:48:17 -07007588sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7589 audio_devices_t type, String8 address) const
7590{
7591 sp<DeviceDescriptor> device;
7592 for (size_t i = 0; i < size(); i++) {
7593 if (itemAt(i)->mDeviceType == type) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007594 if (address == "" || itemAt(i)->mAddress == address) {
7595 device = itemAt(i);
7596 if (itemAt(i)->mAddress == address) {
7597 break;
7598 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007599 }
7600 }
7601 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007602 ALOGV("DeviceVector::getDevice() for type %08x address %s found %p",
Eric Laurent1c333e22014-05-20 10:48:17 -07007603 type, address.string(), device.get());
7604 return device;
7605}
7606
Eric Laurent6a94d692014-05-20 11:18:06 -07007607sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7608 audio_port_handle_t id) const
7609{
7610 sp<DeviceDescriptor> device;
7611 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007612 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007613 if (itemAt(i)->mId == id) {
7614 device = itemAt(i);
7615 break;
7616 }
7617 }
7618 return device;
7619}
7620
Eric Laurent1c333e22014-05-20 10:48:17 -07007621AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7622 audio_devices_t type) const
7623{
7624 DeviceVector devices;
7625 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7626 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7627 devices.add(itemAt(i));
7628 type &= ~itemAt(i)->mDeviceType;
7629 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7630 itemAt(i)->mDeviceType, itemAt(i).get());
7631 }
7632 }
7633 return devices;
7634}
7635
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007636AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7637 audio_devices_t type, String8 address) const
7638{
7639 DeviceVector devices;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007640 for (size_t i = 0; i < size(); i++) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007641 if (itemAt(i)->mDeviceType == type) {
7642 if (itemAt(i)->mAddress == address) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007643 devices.add(itemAt(i));
7644 }
7645 }
7646 }
7647 return devices;
7648}
7649
Eric Laurent1afeecb2014-05-14 08:52:28 -07007650sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7651 const String8& name) const
7652{
7653 sp<DeviceDescriptor> device;
7654 for (size_t i = 0; i < size(); i++) {
7655 if (itemAt(i)->mName == name) {
7656 device = itemAt(i);
7657 break;
7658 }
7659 }
7660 return device;
7661}
7662
Eric Laurent6a94d692014-05-20 11:18:06 -07007663void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7664 struct audio_port_config *dstConfig,
7665 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007666{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007667 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7668 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007669 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007670 }
7671
7672 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7673
Eric Laurent6a94d692014-05-20 11:18:06 -07007674 dstConfig->id = mId;
7675 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007676 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007677 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007678 dstConfig->ext.device.type = mDeviceType;
7679 dstConfig->ext.device.hw_module = mModule->mHandle;
7680 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007681}
7682
7683void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7684{
Eric Laurent83b88082014-06-20 18:31:16 -07007685 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007686 AudioPort::toAudioPort(port);
7687 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007688 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007689 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007690 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007691 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7692}
7693
Eric Laurent1afeecb2014-05-14 08:52:28 -07007694status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007695{
7696 const size_t SIZE = 256;
7697 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007698 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007699
Eric Laurent1afeecb2014-05-14 08:52:28 -07007700 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7701 result.append(buffer);
7702 if (mId != 0) {
7703 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7704 result.append(buffer);
7705 }
7706 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7707 enumToString(sDeviceNameToEnumTable,
7708 ARRAY_SIZE(sDeviceNameToEnumTable),
7709 mDeviceType));
7710 result.append(buffer);
7711 if (mAddress.size() != 0) {
7712 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7713 result.append(buffer);
7714 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007715 write(fd, result.string(), result.size());
7716 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007717
7718 return NO_ERROR;
7719}
7720
Eric Laurent4d416952014-08-10 14:07:09 -07007721status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7722{
7723 const size_t SIZE = 256;
7724 char buffer[SIZE];
7725 String8 result;
7726
7727
7728 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7729 result.append(buffer);
7730 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7731 result.append(buffer);
7732 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7733 result.append(buffer);
7734 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7735 result.append(buffer);
7736 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7737 result.append(buffer);
7738 for (size_t i = 0; i < mPatch.num_sources; i++) {
7739 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7740 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7741 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7742 ARRAY_SIZE(sDeviceNameToEnumTable),
7743 mPatch.sources[i].ext.device.type));
7744 } else {
7745 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7746 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7747 }
7748 result.append(buffer);
7749 }
7750 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7751 result.append(buffer);
7752 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7753 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7754 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7755 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7756 ARRAY_SIZE(sDeviceNameToEnumTable),
7757 mPatch.sinks[i].ext.device.type));
7758 } else {
7759 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7760 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7761 }
7762 result.append(buffer);
7763 }
7764
7765 write(fd, result.string(), result.size());
7766 return NO_ERROR;
7767}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007768
7769// --- audio_policy.conf file parsing
7770
Eric Laurent5dbe4712014-09-19 19:04:57 -07007771uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007772{
7773 uint32_t flag = 0;
7774
7775 // it is OK to cast name to non const here as we are not going to use it after
7776 // strtok() modifies it
7777 char *flagName = strtok(name, "|");
7778 while (flagName != NULL) {
7779 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007780 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7781 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007782 flagName);
7783 }
7784 flagName = strtok(NULL, "|");
7785 }
7786 //force direct flag if offload flag is set: offloading implies a direct output stream
7787 // and all common behaviors are driven by checking only the direct flag
7788 // this should normally be set appropriately in the policy configuration file
7789 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7790 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7791 }
7792
Eric Laurent5dbe4712014-09-19 19:04:57 -07007793 return flag;
7794}
7795
7796uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7797{
7798 uint32_t flag = 0;
7799
7800 // it is OK to cast name to non const here as we are not going to use it after
7801 // strtok() modifies it
7802 char *flagName = strtok(name, "|");
7803 while (flagName != NULL) {
7804 if (strlen(flagName) != 0) {
7805 flag |= stringToEnum(sInputFlagNameToEnumTable,
7806 ARRAY_SIZE(sInputFlagNameToEnumTable),
7807 flagName);
7808 }
7809 flagName = strtok(NULL, "|");
7810 }
7811 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007812}
7813
Eric Laurente0720872014-03-11 09:30:41 -07007814audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007815{
7816 uint32_t device = 0;
7817
7818 char *devName = strtok(name, "|");
7819 while (devName != NULL) {
7820 if (strlen(devName) != 0) {
7821 device |= stringToEnum(sDeviceNameToEnumTable,
7822 ARRAY_SIZE(sDeviceNameToEnumTable),
7823 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007824 }
Eric Laurente552edb2014-03-10 17:42:56 -07007825 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007826 }
Eric Laurente552edb2014-03-10 17:42:56 -07007827 return device;
7828}
7829
Eric Laurente0720872014-03-11 09:30:41 -07007830void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007831{
Eric Laurente552edb2014-03-10 17:42:56 -07007832 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007833 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007834 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007835
Eric Laurent1afeecb2014-05-14 08:52:28 -07007836 node = config_find(root, DEVICES_TAG);
7837 if (node != NULL) {
7838 node = node->first_child;
7839 while (node) {
7840 ALOGV("loadHwModule() loading device %s", node->name);
7841 status_t tmpStatus = module->loadDevice(node);
7842 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7843 status = tmpStatus;
7844 }
7845 node = node->next;
7846 }
7847 }
7848 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007849 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007850 node = node->first_child;
7851 while (node) {
7852 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007853 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007854 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7855 status = tmpStatus;
7856 }
7857 node = node->next;
7858 }
7859 }
7860 node = config_find(root, INPUTS_TAG);
7861 if (node != NULL) {
7862 node = node->first_child;
7863 while (node) {
7864 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007865 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007866 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7867 status = tmpStatus;
7868 }
7869 node = node->next;
7870 }
7871 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007872 loadGlobalConfig(root, module);
7873
Eric Laurente552edb2014-03-10 17:42:56 -07007874 if (status == NO_ERROR) {
7875 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007876 }
7877}
7878
Eric Laurente0720872014-03-11 09:30:41 -07007879void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007880{
7881 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7882 if (node == NULL) {
7883 return;
7884 }
7885
7886 node = node->first_child;
7887 while (node) {
7888 ALOGV("loadHwModules() loading module %s", node->name);
7889 loadHwModule(node);
7890 node = node->next;
7891 }
7892}
7893
Eric Laurent1f2f2232014-06-02 12:01:23 -07007894void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007895{
7896 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007897
Eric Laurente552edb2014-03-10 17:42:56 -07007898 if (node == NULL) {
7899 return;
7900 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007901 DeviceVector declaredDevices;
7902 if (module != NULL) {
7903 declaredDevices = module->mDeclaredDevices;
7904 }
7905
Eric Laurente552edb2014-03-10 17:42:56 -07007906 node = node->first_child;
7907 while (node) {
7908 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007909 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7910 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007911 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7912 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007913 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007914 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007915 ARRAY_SIZE(sDeviceNameToEnumTable),
7916 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007917 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007918 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007919 } else {
7920 ALOGW("loadGlobalConfig() default device not specified");
7921 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007922 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007923 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007924 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7925 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007926 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007927 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7928 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7929 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007930 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7931 uint32_t major, minor;
7932 sscanf((char *)node->value, "%u.%u", &major, &minor);
7933 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7934 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7935 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007936 }
7937 node = node->next;
7938 }
7939}
7940
Eric Laurente0720872014-03-11 09:30:41 -07007941status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007942{
7943 cnode *root;
7944 char *data;
7945
7946 data = (char *)load_file(path, NULL);
7947 if (data == NULL) {
7948 return -ENODEV;
7949 }
7950 root = config_node("", "");
7951 config_load(root, data);
7952
Eric Laurente552edb2014-03-10 17:42:56 -07007953 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007954 // legacy audio_policy.conf files have one global_configuration section
7955 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007956 config_free(root);
7957 free(root);
7958 free(data);
7959
7960 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7961
7962 return NO_ERROR;
7963}
7964
Eric Laurente0720872014-03-11 09:30:41 -07007965void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007966{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007967 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007968 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007969 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7970 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007971 mAvailableOutputDevices.add(mDefaultOutputDevice);
7972 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007973
7974 module = new HwModule("primary");
7975
Eric Laurent1afeecb2014-05-14 08:52:28 -07007976 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007977 profile->mSamplingRates.add(44100);
7978 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7979 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007980 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007981 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7982 module->mOutputProfiles.add(profile);
7983
Eric Laurent1afeecb2014-05-14 08:52:28 -07007984 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007985 profile->mSamplingRates.add(8000);
7986 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7987 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007988 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007989 module->mInputProfiles.add(profile);
7990
7991 mHwModules.add(module);
7992}
7993
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007994audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7995{
7996 // flags to stream type mapping
7997 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7998 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7999 }
8000 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
8001 return AUDIO_STREAM_BLUETOOTH_SCO;
8002 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08008003 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
8004 return AUDIO_STREAM_TTS;
8005 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07008006
8007 // usage to stream type mapping
8008 switch (attr->usage) {
8009 case AUDIO_USAGE_MEDIA:
8010 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07008011 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8012 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08008013 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08008014 if (isStreamActive(AUDIO_STREAM_ALARM)) {
8015 return AUDIO_STREAM_ALARM;
8016 }
8017 if (isStreamActive(AUDIO_STREAM_RING)) {
8018 return AUDIO_STREAM_RING;
8019 }
8020 if (isInCall()) {
8021 return AUDIO_STREAM_VOICE_CALL;
8022 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08008023 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07008024 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8025 return AUDIO_STREAM_SYSTEM;
8026 case AUDIO_USAGE_VOICE_COMMUNICATION:
8027 return AUDIO_STREAM_VOICE_CALL;
8028
8029 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8030 return AUDIO_STREAM_DTMF;
8031
8032 case AUDIO_USAGE_ALARM:
8033 return AUDIO_STREAM_ALARM;
8034 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8035 return AUDIO_STREAM_RING;
8036
8037 case AUDIO_USAGE_NOTIFICATION:
8038 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8039 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8040 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8041 case AUDIO_USAGE_NOTIFICATION_EVENT:
8042 return AUDIO_STREAM_NOTIFICATION;
8043
8044 case AUDIO_USAGE_UNKNOWN:
8045 default:
8046 return AUDIO_STREAM_MUSIC;
8047 }
8048}
Eric Laurente83b55d2014-11-14 10:06:21 -08008049
8050bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
8051 // has flags that map to a strategy?
8052 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8053 return true;
8054 }
8055
8056 // has known usage?
8057 switch (paa->usage) {
8058 case AUDIO_USAGE_UNKNOWN:
8059 case AUDIO_USAGE_MEDIA:
8060 case AUDIO_USAGE_VOICE_COMMUNICATION:
8061 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8062 case AUDIO_USAGE_ALARM:
8063 case AUDIO_USAGE_NOTIFICATION:
8064 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8065 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8066 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8067 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8068 case AUDIO_USAGE_NOTIFICATION_EVENT:
8069 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8070 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8071 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8072 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008073 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08008074 break;
8075 default:
8076 return false;
8077 }
8078 return true;
8079}
8080
Eric Laurente552edb2014-03-10 17:42:56 -07008081}; // namespace android