blob: cd0c16c8fdc037e04018e539bd7404152cb0ae4d [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 Laurentcf2c0212014-07-25 16:20:43 -07001116 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001117 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001118 outputDesc->mSamplingRate = config.sample_rate;
1119 outputDesc->mChannelMask = config.channel_mask;
1120 outputDesc->mFormat = config.format;
1121 outputDesc->mRefCount[stream] = 0;
1122 outputDesc->mStopTime[stream] = 0;
1123 outputDesc->mDirectOpenCount = 1;
1124
Eric Laurente552edb2014-03-10 17:42:56 -07001125 audio_io_handle_t srcOutput = getOutputForEffect();
1126 addOutput(output, outputDesc);
1127 audio_io_handle_t dstOutput = getOutputForEffect();
1128 if (dstOutput == output) {
1129 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1130 }
1131 mPreviousOutputs = mOutputs;
1132 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001133 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001134 return output;
1135 }
1136
Eric Laurentb732cf52014-09-24 19:08:21 -07001137non_direct_output:
1138
Eric Laurente552edb2014-03-10 17:42:56 -07001139 // ignoring channel mask due to downmix capability in mixer
1140
1141 // open a non direct output
1142
1143 // for non direct outputs, only PCM is supported
1144 if (audio_is_linear_pcm(format)) {
1145 // get which output is suitable for the specified stream. The actual
1146 // routing change will happen when startOutput() will be called
1147 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1148
Eric Laurent8838a382014-09-08 16:44:28 -07001149 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1150 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1151 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001152 }
1153 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1154 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1155
1156 ALOGV("getOutput() returns output %d", output);
1157
1158 return output;
1159}
1160
Eric Laurente0720872014-03-11 09:30:41 -07001161audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001162 audio_output_flags_t flags,
1163 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001164{
1165 // select one output among several that provide a path to a particular device or set of
1166 // devices (the list was previously build by getOutputsForDevice()).
1167 // The priority is as follows:
1168 // 1: the output with the highest number of requested policy flags
1169 // 2: the primary output
1170 // 3: the first output in the list
1171
1172 if (outputs.size() == 0) {
1173 return 0;
1174 }
1175 if (outputs.size() == 1) {
1176 return outputs[0];
1177 }
1178
1179 int maxCommonFlags = 0;
1180 audio_io_handle_t outputFlags = 0;
1181 audio_io_handle_t outputPrimary = 0;
1182
1183 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001184 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001185 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001186 // if a valid format is specified, skip output if not compatible
1187 if (format != AUDIO_FORMAT_INVALID) {
1188 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1189 if (format != outputDesc->mFormat) {
1190 continue;
1191 }
1192 } else if (!audio_is_linear_pcm(format)) {
1193 continue;
1194 }
1195 }
1196
Eric Laurent3b73df72014-03-11 09:06:29 -07001197 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001198 if (commonFlags > maxCommonFlags) {
1199 outputFlags = outputs[i];
1200 maxCommonFlags = commonFlags;
1201 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1202 }
1203 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1204 outputPrimary = outputs[i];
1205 }
1206 }
1207 }
1208
1209 if (outputFlags != 0) {
1210 return outputFlags;
1211 }
1212 if (outputPrimary != 0) {
1213 return outputPrimary;
1214 }
1215
1216 return outputs[0];
1217}
1218
Eric Laurente0720872014-03-11 09:30:41 -07001219status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001220 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001221 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001222{
1223 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1224 ssize_t index = mOutputs.indexOfKey(output);
1225 if (index < 0) {
1226 ALOGW("startOutput() unknown output %d", output);
1227 return BAD_VALUE;
1228 }
1229
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001230 // cannot start playback of STREAM_TTS if any other output is being used
1231 uint32_t beaconMuteLatency = 0;
1232 if (stream == AUDIO_STREAM_TTS) {
1233 ALOGV("\t found BEACON stream");
1234 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1235 return INVALID_OPERATION;
1236 } else {
1237 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1238 }
1239 } else {
1240 // some playback other than beacon starts
1241 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1242 }
1243
Eric Laurent1f2f2232014-06-02 12:01:23 -07001244 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001245
1246 // increment usage count for this stream on the requested output:
1247 // NOTE that the usage count is the same for duplicated output and hardware output which is
1248 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1249 outputDesc->changeRefCount(stream, 1);
1250
1251 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001252 // starting an output being rerouted?
1253 audio_devices_t newDevice;
Eric Laurentc722f302014-12-10 11:21:49 -08001254 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001255 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1256 } else {
1257 newDevice = getNewOutputDevice(output, false /*fromCache*/);
1258 }
Eric Laurente552edb2014-03-10 17:42:56 -07001259 routing_strategy strategy = getStrategy(stream);
1260 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001261 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1262 (beaconMuteLatency > 0);
1263 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001264 bool force = false;
1265 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001266 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001267 if (desc != outputDesc) {
1268 // force a device change if any other output is managed by the same hw
1269 // module and has a current device selection that differs from selected device.
1270 // In this case, the audio HAL must receive the new device selection so that it can
1271 // change the device currently selected by the other active output.
1272 if (outputDesc->sharesHwModuleWith(desc) &&
1273 desc->device() != newDevice) {
1274 force = true;
1275 }
1276 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001277 // a notification so that audio focus effect can propagate, or that a mute/unmute
1278 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001279 uint32_t latency = desc->latency();
1280 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1281 waitMs = latency;
1282 }
1283 }
1284 }
1285 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1286
1287 // handle special case for sonification while in call
1288 if (isInCall()) {
1289 handleIncallSonification(stream, true, false);
1290 }
1291
1292 // apply volume rules for current stream and device if necessary
1293 checkAndSetVolume(stream,
1294 mStreams[stream].getVolumeIndex(newDevice),
1295 output,
1296 newDevice);
1297
1298 // update the outputs if starting an output with a stream that can affect notification
1299 // routing
1300 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001301
1302 // Automatically enable the remote submix input when output is started on a re routing mix
1303 // of type MIX_TYPE_RECORDERS
1304 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1305 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001306 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001307 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1308 outputDesc->mPolicyMix->mRegistrationId);
1309 }
1310
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001311 // force reevaluating accessibility routing when ringtone or alarm starts
1312 if (strategy == STRATEGY_SONIFICATION) {
1313 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1314 }
1315
Eric Laurente552edb2014-03-10 17:42:56 -07001316 if (waitMs > muteWaitMs) {
1317 usleep((waitMs - muteWaitMs) * 2 * 1000);
1318 }
1319 }
1320 return NO_ERROR;
1321}
1322
1323
Eric Laurente0720872014-03-11 09:30:41 -07001324status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001325 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001326 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001327{
1328 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1329 ssize_t index = mOutputs.indexOfKey(output);
1330 if (index < 0) {
1331 ALOGW("stopOutput() unknown output %d", output);
1332 return BAD_VALUE;
1333 }
1334
Eric Laurent1f2f2232014-06-02 12:01:23 -07001335 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001336
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001337 // always handle stream stop, check which stream type is stopping
1338 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1339
Eric Laurente552edb2014-03-10 17:42:56 -07001340 // handle special case for sonification while in call
1341 if (isInCall()) {
1342 handleIncallSonification(stream, false, false);
1343 }
1344
1345 if (outputDesc->mRefCount[stream] > 0) {
1346 // decrement usage count of this stream on the output
1347 outputDesc->changeRefCount(stream, -1);
1348 // store time at which the stream was stopped - see isStreamActive()
1349 if (outputDesc->mRefCount[stream] == 0) {
Eric Laurentc722f302014-12-10 11:21:49 -08001350 // Automatically disable the remote submix input when output is stopped on a
1351 // re routing mix of type MIX_TYPE_RECORDERS
1352 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1353 outputDesc->mPolicyMix != NULL &&
1354 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001355 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001356 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1357 outputDesc->mPolicyMix->mRegistrationId);
1358 }
1359
Eric Laurente552edb2014-03-10 17:42:56 -07001360 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001361 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001362 // delay the device switch by twice the latency because stopOutput() is executed when
1363 // the track stop() command is received and at that time the audio track buffer can
1364 // still contain data that needs to be drained. The latency only covers the audio HAL
1365 // and kernel buffers. Also the latency does not always include additional delay in the
1366 // audio path (audio DSP, CODEC ...)
1367 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1368
1369 // force restoring the device selection on other active outputs if it differs from the
1370 // one being selected for this output
1371 for (size_t i = 0; i < mOutputs.size(); i++) {
1372 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001373 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001374 if (curOutput != output &&
1375 desc->isActive() &&
1376 outputDesc->sharesHwModuleWith(desc) &&
1377 (newDevice != desc->device())) {
1378 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001379 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001380 true,
1381 outputDesc->mLatency*2);
1382 }
1383 }
1384 // update the outputs if stopping one with a stream that can affect notification routing
1385 handleNotificationRoutingForStream(stream);
1386 }
1387 return NO_ERROR;
1388 } else {
1389 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1390 return INVALID_OPERATION;
1391 }
1392}
1393
Eric Laurente83b55d2014-11-14 10:06:21 -08001394void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001395 audio_stream_type_t stream __unused,
1396 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001397{
1398 ALOGV("releaseOutput() %d", output);
1399 ssize_t index = mOutputs.indexOfKey(output);
1400 if (index < 0) {
1401 ALOGW("releaseOutput() releasing unknown output %d", output);
1402 return;
1403 }
1404
1405#ifdef AUDIO_POLICY_TEST
1406 int testIndex = testOutputIndex(output);
1407 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001408 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001409 if (outputDesc->isActive()) {
1410 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001411 mOutputs.removeItem(output);
1412 mTestOutputs[testIndex] = 0;
1413 }
1414 return;
1415 }
1416#endif //AUDIO_POLICY_TEST
1417
Eric Laurent1f2f2232014-06-02 12:01:23 -07001418 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001419 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001420 if (desc->mDirectOpenCount <= 0) {
1421 ALOGW("releaseOutput() invalid open count %d for output %d",
1422 desc->mDirectOpenCount, output);
1423 return;
1424 }
1425 if (--desc->mDirectOpenCount == 0) {
1426 closeOutput(output);
1427 // If effects where present on the output, audioflinger moved them to the primary
1428 // output by default: move them back to the appropriate output.
1429 audio_io_handle_t dstOutput = getOutputForEffect();
1430 if (dstOutput != mPrimaryOutput) {
1431 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1432 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001433 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001434 }
1435 }
1436}
1437
1438
Eric Laurentcaf7f482014-11-25 17:50:47 -08001439status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1440 audio_io_handle_t *input,
1441 audio_session_t session,
1442 uint32_t samplingRate,
1443 audio_format_t format,
1444 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001445 audio_input_flags_t flags,
1446 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001447{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001448 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1449 "session %d, flags %#x",
1450 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001451
Eric Laurentcaf7f482014-11-25 17:50:47 -08001452 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001453 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001454 audio_devices_t device;
1455 // handle legacy remote submix case where the address was not always specified
1456 String8 address = String8("");
Eric Laurent5dbe4712014-09-19 19:04:57 -07001457 bool isSoundTrigger = false;
Eric Laurentc447ded2015-01-06 08:47:05 -08001458 audio_source_t inputSource = attr->source;
1459 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001460 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001461
Eric Laurentc447ded2015-01-06 08:47:05 -08001462 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1463 inputSource = AUDIO_SOURCE_MIC;
1464 }
1465 halInputSource = inputSource;
1466
1467 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001468 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
1469 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1470 address = String8(attr->tags + strlen("addr="));
1471 ssize_t index = mPolicyMixes.indexOfKey(address);
1472 if (index < 0) {
1473 ALOGW("getInputForAttr() no policy for address %s", address.string());
1474 return BAD_VALUE;
1475 }
Eric Laurentc722f302014-12-10 11:21:49 -08001476 if (mPolicyMixes[index]->mMix.mMixType != MIX_TYPE_PLAYERS) {
1477 ALOGW("getInputForAttr() bad policy mix type for address %s", address.string());
1478 return BAD_VALUE;
1479 }
1480 policyMix = &mPolicyMixes[index]->mMix;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001481 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001482 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001483 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001484 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001485 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001486 return BAD_VALUE;
1487 }
Eric Laurentc722f302014-12-10 11:21:49 -08001488 if (policyMix != NULL) {
1489 address = policyMix->mRegistrationId;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001490 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1491 // there is an external policy, but this input is attached to a mix of recorders,
1492 // meaning it receives audio injected into the framework, so the recorder doesn't
1493 // know about it and is therefore considered "legacy"
1494 *inputType = API_INPUT_LEGACY;
1495 } else {
1496 // recording a mix of players defined by an external policy, we're rerouting for
1497 // an external policy
1498 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1499 }
Eric Laurentc722f302014-12-10 11:21:49 -08001500 } else if (audio_is_remote_submix_device(device)) {
1501 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001502 *inputType = API_INPUT_MIX_CAPTURE;
1503 } else {
1504 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001505 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001506 // adapt channel selection to input source
Eric Laurentc447ded2015-01-06 08:47:05 -08001507 switch (inputSource) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001508 case AUDIO_SOURCE_VOICE_UPLINK:
1509 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1510 break;
1511 case AUDIO_SOURCE_VOICE_DOWNLINK:
1512 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1513 break;
1514 case AUDIO_SOURCE_VOICE_CALL:
1515 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1516 break;
1517 default:
1518 break;
1519 }
Eric Laurentc447ded2015-01-06 08:47:05 -08001520 if (inputSource == AUDIO_SOURCE_HOTWORD) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001521 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1522 if (index >= 0) {
1523 *input = mSoundTriggerSessions.valueFor(session);
1524 isSoundTrigger = true;
1525 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1526 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
1527 } else {
1528 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1529 }
Eric Laurent5dbe4712014-09-19 19:04:57 -07001530 }
1531 }
1532
Eric Laurent275e8e92014-11-30 15:14:47 -08001533 sp<IOProfile> profile = getInputProfile(device, address,
1534 samplingRate, format, channelMask,
1535 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001536 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001537 //retry without flags
1538 audio_input_flags_t log_flags = flags;
1539 flags = AUDIO_INPUT_FLAG_NONE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001540 profile = getInputProfile(device, address,
1541 samplingRate, format, channelMask,
1542 flags);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001543 if (profile == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001544 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1545 "format %#x, channelMask 0x%X, flags %#x",
Eric Laurent5dbe4712014-09-19 19:04:57 -07001546 device, samplingRate, format, channelMask, log_flags);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001547 return BAD_VALUE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001548 }
Eric Laurente552edb2014-03-10 17:42:56 -07001549 }
1550
1551 if (profile->mModule->mHandle == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001552 ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName);
1553 return NO_INIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001554 }
1555
1556 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1557 config.sample_rate = samplingRate;
1558 config.channel_mask = channelMask;
1559 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001560
Eric Laurentcf2c0212014-07-25 16:20:43 -07001561 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001562 input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001563 &config,
1564 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001565 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001566 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001567 flags);
1568
1569 // only accept input with the exact requested set of parameters
Eric Laurentcaf7f482014-11-25 17:50:47 -08001570 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001571 (samplingRate != config.sample_rate) ||
1572 (format != config.format) ||
1573 (channelMask != config.channel_mask)) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001574 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001575 samplingRate, format, channelMask);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001576 if (*input != AUDIO_IO_HANDLE_NONE) {
1577 mpClientInterface->closeInput(*input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001578 }
Eric Laurentcaf7f482014-11-25 17:50:47 -08001579 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001580 }
1581
Eric Laurent1f2f2232014-06-02 12:01:23 -07001582 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurentc447ded2015-01-06 08:47:05 -08001583 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001584 inputDesc->mRefCount = 0;
1585 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001586 inputDesc->mSamplingRate = samplingRate;
1587 inputDesc->mFormat = format;
1588 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001589 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001590 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001591 inputDesc->mIsSoundTrigger = isSoundTrigger;
Eric Laurentc722f302014-12-10 11:21:49 -08001592 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001593
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001594 ALOGV("getInputForAttr() returns input type = %d", inputType);
1595
Eric Laurentcaf7f482014-11-25 17:50:47 -08001596 addInput(*input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001597 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcaf7f482014-11-25 17:50:47 -08001598 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001599}
1600
Eric Laurent4dc68062014-07-28 17:26:49 -07001601status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1602 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001603{
1604 ALOGV("startInput() input %d", input);
1605 ssize_t index = mInputs.indexOfKey(input);
1606 if (index < 0) {
1607 ALOGW("startInput() unknown input %d", input);
1608 return BAD_VALUE;
1609 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001610 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001611
Eric Laurentc722f302014-12-10 11:21:49 -08001612 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001613 if (index < 0) {
1614 ALOGW("startInput() unknown session %d on input %d", session, input);
1615 return BAD_VALUE;
1616 }
1617
Glenn Kasten74a8e252014-07-24 14:09:55 -07001618 // virtual input devices are compatible with other input devices
1619 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1620
1621 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001622 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001623 if (activeInput != 0 && activeInput != input) {
1624
1625 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1626 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001627 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001628 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001629 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurentc722f302014-12-10 11:21:49 -08001630 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1631 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001632 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001633 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001634 return INVALID_OPERATION;
1635 }
1636 }
1637 }
1638
Glenn Kasten74a8e252014-07-24 14:09:55 -07001639 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001640 if (activeInputsCount() == 0) {
1641 SoundTrigger::setCaptureState(true);
1642 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001643 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001644
Eric Laurentc722f302014-12-10 11:21:49 -08001645 // automatically enable the remote submix output when input is started if not
1646 // used by a policy mix of type MIX_TYPE_RECORDERS
Glenn Kasten74a8e252014-07-24 14:09:55 -07001647 // For remote submix (a virtual device), we open only one input per capture request.
1648 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001649 String8 address = String8("");
1650 if (inputDesc->mPolicyMix == NULL) {
1651 address = String8("0");
1652 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1653 address = inputDesc->mPolicyMix->mRegistrationId;
1654 }
1655 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001656 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001657 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1658 address);
1659 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001660 }
Eric Laurente552edb2014-03-10 17:42:56 -07001661 }
1662
Eric Laurente552edb2014-03-10 17:42:56 -07001663 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1664
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001665 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001666 return NO_ERROR;
1667}
1668
Eric Laurent4dc68062014-07-28 17:26:49 -07001669status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1670 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001671{
1672 ALOGV("stopInput() input %d", input);
1673 ssize_t index = mInputs.indexOfKey(input);
1674 if (index < 0) {
1675 ALOGW("stopInput() unknown input %d", input);
1676 return BAD_VALUE;
1677 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001678 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001679
Eric Laurentc722f302014-12-10 11:21:49 -08001680 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001681 if (index < 0) {
1682 ALOGW("stopInput() unknown session %d on input %d", session, input);
1683 return BAD_VALUE;
1684 }
1685
Eric Laurente552edb2014-03-10 17:42:56 -07001686 if (inputDesc->mRefCount == 0) {
1687 ALOGW("stopInput() input %d already stopped", input);
1688 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001689 }
1690
1691 inputDesc->mRefCount--;
1692 if (inputDesc->mRefCount == 0) {
1693
Eric Laurentc722f302014-12-10 11:21:49 -08001694 // automatically disable the remote submix output when input is stopped if not
1695 // used by a policy mix of type MIX_TYPE_RECORDERS
Eric Laurente552edb2014-03-10 17:42:56 -07001696 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001697 String8 address = String8("");
1698 if (inputDesc->mPolicyMix == NULL) {
1699 address = String8("0");
1700 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1701 address = inputDesc->mPolicyMix->mRegistrationId;
1702 }
1703 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001704 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001705 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1706 address);
1707 }
Eric Laurente552edb2014-03-10 17:42:56 -07001708 }
1709
Eric Laurent1c333e22014-05-20 10:48:17 -07001710 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001711
1712 if (activeInputsCount() == 0) {
1713 SoundTrigger::setCaptureState(false);
1714 }
Eric Laurente552edb2014-03-10 17:42:56 -07001715 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001716 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001717}
1718
Eric Laurent4dc68062014-07-28 17:26:49 -07001719void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1720 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001721{
1722 ALOGV("releaseInput() %d", input);
1723 ssize_t index = mInputs.indexOfKey(input);
1724 if (index < 0) {
1725 ALOGW("releaseInput() releasing unknown input %d", input);
1726 return;
1727 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001728 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1729 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001730
Eric Laurentc722f302014-12-10 11:21:49 -08001731 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001732 if (index < 0) {
1733 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1734 return;
1735 }
Eric Laurentc722f302014-12-10 11:21:49 -08001736 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001737 if (inputDesc->mOpenRefCount == 0) {
1738 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1739 return;
1740 }
1741 inputDesc->mOpenRefCount--;
1742 if (inputDesc->mOpenRefCount > 0) {
1743 ALOGV("releaseInput() exit > 0");
1744 return;
1745 }
1746
Eric Laurent05b90f82014-08-27 15:32:29 -07001747 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001748 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001749 ALOGV("releaseInput() exit");
1750}
1751
Eric Laurentd4692962014-05-05 18:13:44 -07001752void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001753 bool patchRemoved = false;
1754
Eric Laurentd4692962014-05-05 18:13:44 -07001755 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001756 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1757 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1758 if (patch_index >= 0) {
1759 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1760 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1761 mAudioPatches.removeItemsAt(patch_index);
1762 patchRemoved = true;
1763 }
Eric Laurentd4692962014-05-05 18:13:44 -07001764 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1765 }
1766 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001767 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001768
1769 if (patchRemoved) {
1770 mpClientInterface->onAudioPatchListUpdate();
1771 }
Eric Laurentd4692962014-05-05 18:13:44 -07001772}
1773
Eric Laurente0720872014-03-11 09:30:41 -07001774void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001775 int indexMin,
1776 int indexMax)
1777{
1778 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1779 if (indexMin < 0 || indexMin >= indexMax) {
1780 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1781 return;
1782 }
1783 mStreams[stream].mIndexMin = indexMin;
1784 mStreams[stream].mIndexMax = indexMax;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001785 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1786 if (stream == AUDIO_STREAM_MUSIC) {
1787 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1788 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1789 }
Eric Laurente552edb2014-03-10 17:42:56 -07001790}
1791
Eric Laurente0720872014-03-11 09:30:41 -07001792status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001793 int index,
1794 audio_devices_t device)
1795{
1796
1797 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1798 return BAD_VALUE;
1799 }
1800 if (!audio_is_output_device(device)) {
1801 return BAD_VALUE;
1802 }
1803
1804 // Force max volume if stream cannot be muted
1805 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1806
1807 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1808 stream, device, index);
1809
1810 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1811 // clear all device specific values
1812 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1813 mStreams[stream].mIndexCur.clear();
1814 }
1815 mStreams[stream].mIndexCur.add(device, index);
1816
Eric Laurent31551f82014-10-10 18:21:56 -07001817 // update volume on all outputs whose current device is also selected by the same
1818 // strategy as the device specified by the caller
1819 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001820
1821
1822 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1823 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1824 if (stream == AUDIO_STREAM_MUSIC) {
1825 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1826 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1827 }
1828 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1829 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001830 return NO_ERROR;
1831 }
Eric Laurente552edb2014-03-10 17:42:56 -07001832 status_t status = NO_ERROR;
1833 for (size_t i = 0; i < mOutputs.size(); i++) {
1834 audio_devices_t curDevice =
1835 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001836 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001837 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1838 if (volStatus != NO_ERROR) {
1839 status = volStatus;
1840 }
1841 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001842 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1843 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1844 index, mOutputs.keyAt(i), curDevice);
1845 }
Eric Laurente552edb2014-03-10 17:42:56 -07001846 }
1847 return status;
1848}
1849
Eric Laurente0720872014-03-11 09:30:41 -07001850status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001851 int *index,
1852 audio_devices_t device)
1853{
1854 if (index == NULL) {
1855 return BAD_VALUE;
1856 }
1857 if (!audio_is_output_device(device)) {
1858 return BAD_VALUE;
1859 }
1860 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1861 // the strategy the stream belongs to.
1862 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1863 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1864 }
1865 device = getDeviceForVolume(device);
1866
1867 *index = mStreams[stream].getVolumeIndex(device);
1868 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1869 return NO_ERROR;
1870}
1871
Eric Laurente0720872014-03-11 09:30:41 -07001872audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001873 const SortedVector<audio_io_handle_t>& outputs)
1874{
1875 // select one output among several suitable for global effects.
1876 // The priority is as follows:
1877 // 1: An offloaded output. If the effect ends up not being offloadable,
1878 // AudioFlinger will invalidate the track and the offloaded output
1879 // will be closed causing the effect to be moved to a PCM output.
1880 // 2: A deep buffer output
1881 // 3: the first output in the list
1882
1883 if (outputs.size() == 0) {
1884 return 0;
1885 }
1886
1887 audio_io_handle_t outputOffloaded = 0;
1888 audio_io_handle_t outputDeepBuffer = 0;
1889
1890 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001891 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001892 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001893 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1894 outputOffloaded = outputs[i];
1895 }
1896 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1897 outputDeepBuffer = outputs[i];
1898 }
1899 }
1900
1901 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1902 outputOffloaded, outputDeepBuffer);
1903 if (outputOffloaded != 0) {
1904 return outputOffloaded;
1905 }
1906 if (outputDeepBuffer != 0) {
1907 return outputDeepBuffer;
1908 }
1909
1910 return outputs[0];
1911}
1912
Eric Laurente0720872014-03-11 09:30:41 -07001913audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001914{
1915 // apply simple rule where global effects are attached to the same output as MUSIC streams
1916
Eric Laurent3b73df72014-03-11 09:06:29 -07001917 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001918 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1919 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1920
1921 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1922 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1923 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1924
1925 return output;
1926}
1927
Eric Laurente0720872014-03-11 09:30:41 -07001928status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001929 audio_io_handle_t io,
1930 uint32_t strategy,
1931 int session,
1932 int id)
1933{
1934 ssize_t index = mOutputs.indexOfKey(io);
1935 if (index < 0) {
1936 index = mInputs.indexOfKey(io);
1937 if (index < 0) {
1938 ALOGW("registerEffect() unknown io %d", io);
1939 return INVALID_OPERATION;
1940 }
1941 }
1942
1943 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1944 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1945 desc->name, desc->memoryUsage);
1946 return INVALID_OPERATION;
1947 }
1948 mTotalEffectsMemory += desc->memoryUsage;
1949 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1950 desc->name, io, strategy, session, id);
1951 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1952
Eric Laurent1f2f2232014-06-02 12:01:23 -07001953 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1954 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1955 effectDesc->mIo = io;
1956 effectDesc->mStrategy = (routing_strategy)strategy;
1957 effectDesc->mSession = session;
1958 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001959
Eric Laurent1f2f2232014-06-02 12:01:23 -07001960 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001961
1962 return NO_ERROR;
1963}
1964
Eric Laurente0720872014-03-11 09:30:41 -07001965status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001966{
1967 ssize_t index = mEffects.indexOfKey(id);
1968 if (index < 0) {
1969 ALOGW("unregisterEffect() unknown effect ID %d", id);
1970 return INVALID_OPERATION;
1971 }
1972
Eric Laurent1f2f2232014-06-02 12:01:23 -07001973 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001974
Eric Laurent1f2f2232014-06-02 12:01:23 -07001975 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001976
Eric Laurent1f2f2232014-06-02 12:01:23 -07001977 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001978 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001979 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1980 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001981 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001982 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001983 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001984 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001985
1986 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001987
1988 return NO_ERROR;
1989}
1990
Eric Laurente0720872014-03-11 09:30:41 -07001991status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001992{
1993 ssize_t index = mEffects.indexOfKey(id);
1994 if (index < 0) {
1995 ALOGW("unregisterEffect() unknown effect ID %d", id);
1996 return INVALID_OPERATION;
1997 }
1998
1999 return setEffectEnabled(mEffects.valueAt(index), enabled);
2000}
2001
Eric Laurent1f2f2232014-06-02 12:01:23 -07002002status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07002003{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002004 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07002005 ALOGV("setEffectEnabled(%s) effect already %s",
2006 enabled?"true":"false", enabled?"enabled":"disabled");
2007 return INVALID_OPERATION;
2008 }
2009
2010 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002011 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002012 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002013 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07002014 return INVALID_OPERATION;
2015 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002016 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002017 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
2018 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002019 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07002020 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002021 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
2022 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002023 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002024 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002025 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
2026 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002027 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07002028 return NO_ERROR;
2029}
2030
Eric Laurente0720872014-03-11 09:30:41 -07002031bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07002032{
2033 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002034 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
2035 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
2036 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002037 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002038 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07002039 return true;
2040 }
2041 }
2042 return false;
2043}
2044
Eric Laurente0720872014-03-11 09:30:41 -07002045bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002046{
2047 nsecs_t sysTime = systemTime();
2048 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002049 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07002050 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002051 return true;
2052 }
2053 }
2054 return false;
2055}
2056
Eric Laurente0720872014-03-11 09:30:41 -07002057bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07002058 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002059{
2060 nsecs_t sysTime = systemTime();
2061 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002062 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002063 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002064 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurentc722f302014-12-10 11:21:49 -08002065 // do not consider re routing (when the output is going to a dynamic policy)
2066 // as "remote playback"
2067 if (outputDesc->mPolicyMix == NULL) {
Jean-Michel Trivi1767df72014-12-09 18:11:49 -08002068 return true;
2069 }
Eric Laurente552edb2014-03-10 17:42:56 -07002070 }
2071 }
2072 return false;
2073}
2074
Eric Laurente0720872014-03-11 09:30:41 -07002075bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002076{
2077 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002078 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurenta34c9ce2014-12-19 11:16:32 -08002079 if (inputDescriptor->mRefCount == 0) {
2080 continue;
2081 }
2082 if (inputDescriptor->mInputSource == (int)source) {
Eric Laurente552edb2014-03-10 17:42:56 -07002083 return true;
2084 }
Eric Laurenta34c9ce2014-12-19 11:16:32 -08002085 // AUDIO_SOURCE_HOTWORD is equivalent to AUDIO_SOURCE_VOICE_RECOGNITION only if it
2086 // corresponds to an active capture triggered by a hardware hotword recognition
2087 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) &&
2088 (inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD)) {
2089 // FIXME: we should not assume that the first session is the active one and keep
2090 // activity count per session. Same in startInput().
2091 ssize_t index = mSoundTriggerSessions.indexOfKey(inputDescriptor->mSessions.itemAt(0));
2092 if (index >= 0) {
2093 return true;
2094 }
2095 }
Eric Laurente552edb2014-03-10 17:42:56 -07002096 }
2097 return false;
2098}
2099
Eric Laurent275e8e92014-11-30 15:14:47 -08002100// Register a list of custom mixes with their attributes and format.
2101// When a mix is registered, corresponding input and output profiles are
2102// added to the remote submix hw module. The profile contains only the
2103// parameters (sampling rate, format...) specified by the mix.
2104// The corresponding input remote submix device is also connected.
2105//
2106// When a remote submix device is connected, the address is checked to select the
2107// appropriate profile and the corresponding input or output stream is opened.
2108//
2109// When capture starts, getInputForAttr() will:
2110// - 1 look for a mix matching the address passed in attribtutes tags if any
2111// - 2 if none found, getDeviceForInputSource() will:
2112// - 2.1 look for a mix matching the attributes source
2113// - 2.2 if none found, default to device selection by policy rules
2114// At this time, the corresponding output remote submix device is also connected
2115// and active playback use cases can be transferred to this mix if needed when reconnecting
2116// after AudioTracks are invalidated
2117//
2118// When playback starts, getOutputForAttr() will:
2119// - 1 look for a mix matching the address passed in attribtutes tags if any
2120// - 2 if none found, look for a mix matching the attributes usage
2121// - 3 if none found, default to device and output selection by policy rules.
2122
2123status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2124{
2125 sp<HwModule> module;
2126 for (size_t i = 0; i < mHwModules.size(); i++) {
2127 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2128 mHwModules[i]->mHandle != 0) {
2129 module = mHwModules[i];
2130 break;
2131 }
2132 }
2133
2134 if (module == 0) {
2135 return INVALID_OPERATION;
2136 }
2137
2138 ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
2139
2140 for (size_t i = 0; i < mixes.size(); i++) {
2141 String8 address = mixes[i].mRegistrationId;
2142 ssize_t index = mPolicyMixes.indexOfKey(address);
2143 if (index >= 0) {
2144 ALOGE("registerPolicyMixes(): mix for address %s already registered", address.string());
2145 continue;
2146 }
2147 audio_config_t outputConfig = mixes[i].mFormat;
2148 audio_config_t inputConfig = mixes[i].mFormat;
2149 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2150 // stereo and let audio flinger do the channel conversion if needed.
2151 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2152 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2153 module->addOutputProfile(address, &outputConfig,
2154 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2155 module->addInputProfile(address, &inputConfig,
2156 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2157 sp<AudioPolicyMix> policyMix = new AudioPolicyMix();
2158 policyMix->mMix = mixes[i];
2159 mPolicyMixes.add(address, policyMix);
Eric Laurentc722f302014-12-10 11:21:49 -08002160 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002161 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002162 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2163 address.string());
2164 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002165 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002166 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2167 address.string());
2168 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002169 }
2170 return NO_ERROR;
2171}
2172
2173status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2174{
2175 sp<HwModule> module;
2176 for (size_t i = 0; i < mHwModules.size(); i++) {
2177 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2178 mHwModules[i]->mHandle != 0) {
2179 module = mHwModules[i];
2180 break;
2181 }
2182 }
2183
2184 if (module == 0) {
2185 return INVALID_OPERATION;
2186 }
2187
2188 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
2189
2190 for (size_t i = 0; i < mixes.size(); i++) {
2191 String8 address = mixes[i].mRegistrationId;
2192 ssize_t index = mPolicyMixes.indexOfKey(address);
2193 if (index < 0) {
2194 ALOGE("unregisterPolicyMixes(): mix for address %s not registered", address.string());
2195 continue;
2196 }
2197
2198 mPolicyMixes.removeItemsAt(index);
2199
Eric Laurentc722f302014-12-10 11:21:49 -08002200 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2201 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2202 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002203 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002204 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2205 address.string());
2206 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002207
2208 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2209 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2210 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002211 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08002212 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2213 address.string());
2214 }
2215 module->removeOutputProfile(address);
2216 module->removeInputProfile(address);
2217 }
2218 return NO_ERROR;
2219}
2220
Eric Laurente552edb2014-03-10 17:42:56 -07002221
Eric Laurente0720872014-03-11 09:30:41 -07002222status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002223{
2224 const size_t SIZE = 256;
2225 char buffer[SIZE];
2226 String8 result;
2227
2228 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2229 result.append(buffer);
2230
2231 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
2232 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002233 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
2234 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002235 snprintf(buffer, SIZE, " Force use for communications %d\n",
2236 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07002237 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002238 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07002239 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002240 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
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 dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
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 system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07002245 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002246 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2247 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
2248 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002249
Eric Laurent3a4311c2014-03-17 12:00:47 -07002250 snprintf(buffer, SIZE, " Available output devices:\n");
2251 result.append(buffer);
2252 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002253 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002254 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002255 }
2256 snprintf(buffer, SIZE, "\n Available input devices:\n");
2257 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07002258 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002259 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002260 }
Eric Laurente552edb2014-03-10 17:42:56 -07002261
2262 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
2263 write(fd, buffer, strlen(buffer));
2264 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002265 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002266 write(fd, buffer, strlen(buffer));
2267 mHwModules[i]->dump(fd);
2268 }
2269
2270 snprintf(buffer, SIZE, "\nOutputs dump:\n");
2271 write(fd, buffer, strlen(buffer));
2272 for (size_t i = 0; i < mOutputs.size(); i++) {
2273 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
2274 write(fd, buffer, strlen(buffer));
2275 mOutputs.valueAt(i)->dump(fd);
2276 }
2277
2278 snprintf(buffer, SIZE, "\nInputs dump:\n");
2279 write(fd, buffer, strlen(buffer));
2280 for (size_t i = 0; i < mInputs.size(); i++) {
2281 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
2282 write(fd, buffer, strlen(buffer));
2283 mInputs.valueAt(i)->dump(fd);
2284 }
2285
2286 snprintf(buffer, SIZE, "\nStreams dump:\n");
2287 write(fd, buffer, strlen(buffer));
2288 snprintf(buffer, SIZE,
2289 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
2290 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002291 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002292 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07002293 write(fd, buffer, strlen(buffer));
2294 mStreams[i].dump(fd);
2295 }
2296
2297 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2298 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2299 write(fd, buffer, strlen(buffer));
2300
2301 snprintf(buffer, SIZE, "Registered effects:\n");
2302 write(fd, buffer, strlen(buffer));
2303 for (size_t i = 0; i < mEffects.size(); i++) {
2304 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2305 write(fd, buffer, strlen(buffer));
2306 mEffects.valueAt(i)->dump(fd);
2307 }
2308
Eric Laurent4d416952014-08-10 14:07:09 -07002309 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2310 write(fd, buffer, strlen(buffer));
2311 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2312 mAudioPatches[i]->dump(fd, 2, i);
2313 }
Eric Laurente552edb2014-03-10 17:42:56 -07002314
2315 return NO_ERROR;
2316}
2317
2318// This function checks for the parameters which can be offloaded.
2319// This can be enhanced depending on the capability of the DSP and policy
2320// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002321bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002322{
2323 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002324 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002325 offloadInfo.sample_rate, offloadInfo.channel_mask,
2326 offloadInfo.format,
2327 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2328 offloadInfo.has_video);
2329
2330 // Check if offload has been disabled
2331 char propValue[PROPERTY_VALUE_MAX];
2332 if (property_get("audio.offload.disable", propValue, "0")) {
2333 if (atoi(propValue) != 0) {
2334 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2335 return false;
2336 }
2337 }
2338
2339 // Check if stream type is music, then only allow offload as of now.
2340 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2341 {
2342 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2343 return false;
2344 }
2345
2346 //TODO: enable audio offloading with video when ready
2347 if (offloadInfo.has_video)
2348 {
2349 ALOGV("isOffloadSupported: has_video == true, returning false");
2350 return false;
2351 }
2352
2353 //If duration is less than minimum value defined in property, return false
2354 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2355 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2356 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2357 return false;
2358 }
2359 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2360 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2361 return false;
2362 }
2363
2364 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2365 // creating an offloaded track and tearing it down immediately after start when audioflinger
2366 // detects there is an active non offloadable effect.
2367 // FIXME: We should check the audio session here but we do not have it in this context.
2368 // This may prevent offloading in rare situations where effects are left active by apps
2369 // in the background.
2370 if (isNonOffloadableEffectEnabled()) {
2371 return false;
2372 }
2373
2374 // See if there is a profile to support this.
2375 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002376 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002377 offloadInfo.sample_rate,
2378 offloadInfo.format,
2379 offloadInfo.channel_mask,
2380 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002381 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2382 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002383}
2384
Eric Laurent6a94d692014-05-20 11:18:06 -07002385status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2386 audio_port_type_t type,
2387 unsigned int *num_ports,
2388 struct audio_port *ports,
2389 unsigned int *generation)
2390{
2391 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2392 generation == NULL) {
2393 return BAD_VALUE;
2394 }
2395 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2396 if (ports == NULL) {
2397 *num_ports = 0;
2398 }
2399
2400 size_t portsWritten = 0;
2401 size_t portsMax = *num_ports;
2402 *num_ports = 0;
2403 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2404 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2405 for (size_t i = 0;
2406 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2407 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2408 }
2409 *num_ports += mAvailableOutputDevices.size();
2410 }
2411 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2412 for (size_t i = 0;
2413 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2414 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2415 }
2416 *num_ports += mAvailableInputDevices.size();
2417 }
2418 }
2419 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2420 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2421 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2422 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2423 }
2424 *num_ports += mInputs.size();
2425 }
2426 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002427 size_t numOutputs = 0;
2428 for (size_t i = 0; i < mOutputs.size(); i++) {
2429 if (!mOutputs[i]->isDuplicated()) {
2430 numOutputs++;
2431 if (portsWritten < portsMax) {
2432 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2433 }
2434 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002435 }
Eric Laurent84c70242014-06-23 08:46:27 -07002436 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002437 }
2438 }
2439 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002440 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002441 return NO_ERROR;
2442}
2443
2444status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2445{
2446 return NO_ERROR;
2447}
2448
Eric Laurent1f2f2232014-06-02 12:01:23 -07002449sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002450 audio_port_handle_t id) const
2451{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002452 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002453 for (size_t i = 0; i < mOutputs.size(); i++) {
2454 outputDesc = mOutputs.valueAt(i);
2455 if (outputDesc->mId == id) {
2456 break;
2457 }
2458 }
2459 return outputDesc;
2460}
2461
Eric Laurent1f2f2232014-06-02 12:01:23 -07002462sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002463 audio_port_handle_t id) const
2464{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002465 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002466 for (size_t i = 0; i < mInputs.size(); i++) {
2467 inputDesc = mInputs.valueAt(i);
2468 if (inputDesc->mId == id) {
2469 break;
2470 }
2471 }
2472 return inputDesc;
2473}
2474
Eric Laurent1f2f2232014-06-02 12:01:23 -07002475sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2476 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002477{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002478 sp <HwModule> module;
2479
Eric Laurent6a94d692014-05-20 11:18:06 -07002480 for (size_t i = 0; i < mHwModules.size(); i++) {
2481 if (mHwModules[i]->mHandle == 0) {
2482 continue;
2483 }
2484 if (audio_is_output_device(device)) {
2485 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2486 {
2487 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2488 return mHwModules[i];
2489 }
2490 }
2491 } else {
2492 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2493 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2494 device & ~AUDIO_DEVICE_BIT_IN) {
2495 return mHwModules[i];
2496 }
2497 }
2498 }
2499 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002500 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002501}
2502
Eric Laurent1f2f2232014-06-02 12:01:23 -07002503sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002504{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002505 sp <HwModule> module;
2506
Eric Laurent1afeecb2014-05-14 08:52:28 -07002507 for (size_t i = 0; i < mHwModules.size(); i++)
2508 {
2509 if (strcmp(mHwModules[i]->mName, name) == 0) {
2510 return mHwModules[i];
2511 }
2512 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002513 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002514}
2515
Eric Laurentc2730ba2014-07-20 15:47:07 -07002516audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2517{
2518 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2519 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2520 return devices & mAvailableOutputDevices.types();
2521}
2522
2523audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2524{
2525 audio_module_handle_t primaryHandle =
2526 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2527 audio_devices_t devices = AUDIO_DEVICE_NONE;
2528 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2529 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2530 devices |= mAvailableInputDevices[i]->mDeviceType;
2531 }
2532 }
2533 return devices;
2534}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002535
Eric Laurent6a94d692014-05-20 11:18:06 -07002536status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2537 audio_patch_handle_t *handle,
2538 uid_t uid)
2539{
2540 ALOGV("createAudioPatch()");
2541
2542 if (handle == NULL || patch == NULL) {
2543 return BAD_VALUE;
2544 }
2545 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2546
Eric Laurent874c42872014-08-08 15:13:39 -07002547 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2548 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2549 return BAD_VALUE;
2550 }
2551 // only one source per audio patch supported for now
2552 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002553 return INVALID_OPERATION;
2554 }
Eric Laurent874c42872014-08-08 15:13:39 -07002555
2556 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002557 return INVALID_OPERATION;
2558 }
Eric Laurent874c42872014-08-08 15:13:39 -07002559 for (size_t i = 0; i < patch->num_sinks; i++) {
2560 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2561 return INVALID_OPERATION;
2562 }
2563 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002564
2565 sp<AudioPatch> patchDesc;
2566 ssize_t index = mAudioPatches.indexOfKey(*handle);
2567
Eric Laurent6a94d692014-05-20 11:18:06 -07002568 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2569 patch->sources[0].role,
2570 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002571#if LOG_NDEBUG == 0
2572 for (size_t i = 0; i < patch->num_sinks; i++) {
2573 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2574 patch->sinks[i].role,
2575 patch->sinks[i].type);
2576 }
2577#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002578
2579 if (index >= 0) {
2580 patchDesc = mAudioPatches.valueAt(index);
2581 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2582 mUidCached, patchDesc->mUid, uid);
2583 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2584 return INVALID_OPERATION;
2585 }
2586 } else {
2587 *handle = 0;
2588 }
2589
2590 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002591 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002592 if (outputDesc == NULL) {
2593 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2594 return BAD_VALUE;
2595 }
Eric Laurent84c70242014-06-23 08:46:27 -07002596 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2597 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002598 if (patchDesc != 0) {
2599 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2600 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2601 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2602 return BAD_VALUE;
2603 }
2604 }
Eric Laurent874c42872014-08-08 15:13:39 -07002605 DeviceVector devices;
2606 for (size_t i = 0; i < patch->num_sinks; i++) {
2607 // Only support mix to devices connection
2608 // TODO add support for mix to mix connection
2609 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2610 ALOGV("createAudioPatch() source mix but sink is not a device");
2611 return INVALID_OPERATION;
2612 }
2613 sp<DeviceDescriptor> devDesc =
2614 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2615 if (devDesc == 0) {
2616 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2617 return BAD_VALUE;
2618 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002619
Eric Laurent874c42872014-08-08 15:13:39 -07002620 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002621 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002622 patch->sources[0].sample_rate,
2623 NULL, // updatedSamplingRate
2624 patch->sources[0].format,
2625 patch->sources[0].channel_mask,
2626 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2627 ALOGV("createAudioPatch() profile not supported for device %08x",
2628 devDesc->mDeviceType);
2629 return INVALID_OPERATION;
2630 }
2631 devices.add(devDesc);
2632 }
2633 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002634 return INVALID_OPERATION;
2635 }
Eric Laurent874c42872014-08-08 15:13:39 -07002636
Eric Laurent6a94d692014-05-20 11:18:06 -07002637 // TODO: reconfigure output format and channels here
2638 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002639 devices.types(), outputDesc->mIoHandle);
2640 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002641 index = mAudioPatches.indexOfKey(*handle);
2642 if (index >= 0) {
2643 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2644 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2645 }
2646 patchDesc = mAudioPatches.valueAt(index);
2647 patchDesc->mUid = uid;
2648 ALOGV("createAudioPatch() success");
2649 } else {
2650 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2651 return INVALID_OPERATION;
2652 }
2653 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2654 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2655 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002656 // only one sink supported when connecting an input device to a mix
2657 if (patch->num_sinks > 1) {
2658 return INVALID_OPERATION;
2659 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002660 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002661 if (inputDesc == NULL) {
2662 return BAD_VALUE;
2663 }
2664 if (patchDesc != 0) {
2665 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2666 return BAD_VALUE;
2667 }
2668 }
2669 sp<DeviceDescriptor> devDesc =
2670 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2671 if (devDesc == 0) {
2672 return BAD_VALUE;
2673 }
2674
Eric Laurent84c70242014-06-23 08:46:27 -07002675 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002676 devDesc->mAddress,
2677 patch->sinks[0].sample_rate,
2678 NULL, /*updatedSampleRate*/
2679 patch->sinks[0].format,
2680 patch->sinks[0].channel_mask,
2681 // FIXME for the parameter type,
2682 // and the NONE
2683 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002684 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002685 return INVALID_OPERATION;
2686 }
2687 // TODO: reconfigure output format and channels here
2688 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002689 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002690 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002691 index = mAudioPatches.indexOfKey(*handle);
2692 if (index >= 0) {
2693 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2694 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2695 }
2696 patchDesc = mAudioPatches.valueAt(index);
2697 patchDesc->mUid = uid;
2698 ALOGV("createAudioPatch() success");
2699 } else {
2700 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2701 return INVALID_OPERATION;
2702 }
2703 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2704 // device to device connection
2705 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002706 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002707 return BAD_VALUE;
2708 }
2709 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002710 sp<DeviceDescriptor> srcDeviceDesc =
2711 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002712 if (srcDeviceDesc == 0) {
2713 return BAD_VALUE;
2714 }
Eric Laurent874c42872014-08-08 15:13:39 -07002715
Eric Laurent6a94d692014-05-20 11:18:06 -07002716 //update source and sink with our own data as the data passed in the patch may
2717 // be incomplete.
2718 struct audio_patch newPatch = *patch;
2719 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002720
Eric Laurent874c42872014-08-08 15:13:39 -07002721 for (size_t i = 0; i < patch->num_sinks; i++) {
2722 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2723 ALOGV("createAudioPatch() source device but one sink is not a device");
2724 return INVALID_OPERATION;
2725 }
2726
2727 sp<DeviceDescriptor> sinkDeviceDesc =
2728 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2729 if (sinkDeviceDesc == 0) {
2730 return BAD_VALUE;
2731 }
2732 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2733
2734 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2735 // only one sink supported when connected devices across HW modules
2736 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002737 return INVALID_OPERATION;
2738 }
Eric Laurent874c42872014-08-08 15:13:39 -07002739 SortedVector<audio_io_handle_t> outputs =
2740 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2741 mOutputs);
2742 // if the sink device is reachable via an opened output stream, request to go via
2743 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002744 audio_io_handle_t output = selectOutput(outputs,
2745 AUDIO_OUTPUT_FLAG_NONE,
2746 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002747 if (output != AUDIO_IO_HANDLE_NONE) {
2748 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2749 if (outputDesc->isDuplicated()) {
2750 return INVALID_OPERATION;
2751 }
2752 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2753 newPatch.num_sources = 2;
2754 }
Eric Laurent83b88082014-06-20 18:31:16 -07002755 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002756 }
2757 // TODO: check from routing capabilities in config file and other conflicting patches
2758
2759 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2760 if (index >= 0) {
2761 afPatchHandle = patchDesc->mAfPatchHandle;
2762 }
2763
2764 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2765 &afPatchHandle,
2766 0);
2767 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2768 status, afPatchHandle);
2769 if (status == NO_ERROR) {
2770 if (index < 0) {
2771 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2772 &newPatch, uid);
2773 addAudioPatch(patchDesc->mHandle, patchDesc);
2774 } else {
2775 patchDesc->mPatch = newPatch;
2776 }
2777 patchDesc->mAfPatchHandle = afPatchHandle;
2778 *handle = patchDesc->mHandle;
2779 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002780 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002781 } else {
2782 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2783 status);
2784 return INVALID_OPERATION;
2785 }
2786 } else {
2787 return BAD_VALUE;
2788 }
2789 } else {
2790 return BAD_VALUE;
2791 }
2792 return NO_ERROR;
2793}
2794
2795status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2796 uid_t uid)
2797{
2798 ALOGV("releaseAudioPatch() patch %d", handle);
2799
2800 ssize_t index = mAudioPatches.indexOfKey(handle);
2801
2802 if (index < 0) {
2803 return BAD_VALUE;
2804 }
2805 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2806 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2807 mUidCached, patchDesc->mUid, uid);
2808 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2809 return INVALID_OPERATION;
2810 }
2811
2812 struct audio_patch *patch = &patchDesc->mPatch;
2813 patchDesc->mUid = mUidCached;
2814 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002815 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002816 if (outputDesc == NULL) {
2817 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2818 return BAD_VALUE;
2819 }
2820
2821 setOutputDevice(outputDesc->mIoHandle,
2822 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2823 true,
2824 0,
2825 NULL);
2826 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2827 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002828 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002829 if (inputDesc == NULL) {
2830 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2831 return BAD_VALUE;
2832 }
2833 setInputDevice(inputDesc->mIoHandle,
2834 getNewInputDevice(inputDesc->mIoHandle),
2835 true,
2836 NULL);
2837 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2838 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2839 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2840 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2841 status, patchDesc->mAfPatchHandle);
2842 removeAudioPatch(patchDesc->mHandle);
2843 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002844 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002845 } else {
2846 return BAD_VALUE;
2847 }
2848 } else {
2849 return BAD_VALUE;
2850 }
2851 return NO_ERROR;
2852}
2853
2854status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2855 struct audio_patch *patches,
2856 unsigned int *generation)
2857{
2858 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2859 generation == NULL) {
2860 return BAD_VALUE;
2861 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002862 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002863 *num_patches, patches, mAudioPatches.size());
2864 if (patches == NULL) {
2865 *num_patches = 0;
2866 }
2867
2868 size_t patchesWritten = 0;
2869 size_t patchesMax = *num_patches;
2870 for (size_t i = 0;
2871 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2872 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2873 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002874 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002875 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2876 }
2877 *num_patches = mAudioPatches.size();
2878
2879 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002880 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002881 return NO_ERROR;
2882}
2883
Eric Laurente1715a42014-05-20 11:30:42 -07002884status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002885{
Eric Laurente1715a42014-05-20 11:30:42 -07002886 ALOGV("setAudioPortConfig()");
2887
2888 if (config == NULL) {
2889 return BAD_VALUE;
2890 }
2891 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2892 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002893 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2894 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002895 }
2896
Eric Laurenta121f902014-06-03 13:32:54 -07002897 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002898 if (config->type == AUDIO_PORT_TYPE_MIX) {
2899 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002900 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002901 if (outputDesc == NULL) {
2902 return BAD_VALUE;
2903 }
Eric Laurent84c70242014-06-23 08:46:27 -07002904 ALOG_ASSERT(!outputDesc->isDuplicated(),
2905 "setAudioPortConfig() called on duplicated output %d",
2906 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002907 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002908 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002909 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002910 if (inputDesc == NULL) {
2911 return BAD_VALUE;
2912 }
Eric Laurenta121f902014-06-03 13:32:54 -07002913 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002914 } else {
2915 return BAD_VALUE;
2916 }
2917 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2918 sp<DeviceDescriptor> deviceDesc;
2919 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2920 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2921 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2922 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2923 } else {
2924 return BAD_VALUE;
2925 }
2926 if (deviceDesc == NULL) {
2927 return BAD_VALUE;
2928 }
Eric Laurenta121f902014-06-03 13:32:54 -07002929 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002930 } else {
2931 return BAD_VALUE;
2932 }
2933
Eric Laurenta121f902014-06-03 13:32:54 -07002934 struct audio_port_config backupConfig;
2935 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2936 if (status == NO_ERROR) {
2937 struct audio_port_config newConfig;
2938 audioPortConfig->toAudioPortConfig(&newConfig, config);
2939 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002940 }
Eric Laurenta121f902014-06-03 13:32:54 -07002941 if (status != NO_ERROR) {
2942 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002943 }
Eric Laurente1715a42014-05-20 11:30:42 -07002944
2945 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002946}
2947
2948void AudioPolicyManager::clearAudioPatches(uid_t uid)
2949{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002950 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002951 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2952 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002953 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002954 }
2955 }
2956}
2957
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002958status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2959 audio_io_handle_t *ioHandle,
2960 audio_devices_t *device)
2961{
2962 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2963 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002964 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002965
2966 mSoundTriggerSessions.add(*session, *ioHandle);
2967
2968 return NO_ERROR;
2969}
2970
2971status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2972{
2973 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2974 if (index < 0) {
2975 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2976 return BAD_VALUE;
2977 }
2978
2979 mSoundTriggerSessions.removeItem(session);
2980 return NO_ERROR;
2981}
2982
Eric Laurent6a94d692014-05-20 11:18:06 -07002983status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2984 const sp<AudioPatch>& patch)
2985{
2986 ssize_t index = mAudioPatches.indexOfKey(handle);
2987
2988 if (index >= 0) {
2989 ALOGW("addAudioPatch() patch %d already in", handle);
2990 return ALREADY_EXISTS;
2991 }
2992 mAudioPatches.add(handle, patch);
2993 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2994 "sink handle %d",
2995 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2996 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2997 return NO_ERROR;
2998}
2999
3000status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
3001{
3002 ssize_t index = mAudioPatches.indexOfKey(handle);
3003
3004 if (index < 0) {
3005 ALOGW("removeAudioPatch() patch %d not in", handle);
3006 return ALREADY_EXISTS;
3007 }
3008 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
3009 mAudioPatches.valueAt(index)->mAfPatchHandle);
3010 mAudioPatches.removeItemsAt(index);
3011 return NO_ERROR;
3012}
3013
Eric Laurente552edb2014-03-10 17:42:56 -07003014// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003015// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003016// ----------------------------------------------------------------------------
3017
Eric Laurent3a4311c2014-03-17 12:00:47 -07003018uint32_t AudioPolicyManager::nextUniqueId()
3019{
3020 return android_atomic_inc(&mNextUniqueId);
3021}
3022
Eric Laurent6a94d692014-05-20 11:18:06 -07003023uint32_t AudioPolicyManager::nextAudioPortGeneration()
3024{
3025 return android_atomic_inc(&mAudioPortGeneration);
3026}
3027
Eric Laurente0720872014-03-11 09:30:41 -07003028AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003029 :
3030#ifdef AUDIO_POLICY_TEST
3031 Thread(false),
3032#endif //AUDIO_POLICY_TEST
3033 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07003034 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07003035 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
3036 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003037 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07003038 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003039 mAudioPortGeneration(1),
3040 mBeaconMuteRefCount(0),
3041 mBeaconPlayingRefCount(0),
3042 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003043{
Eric Laurent6a94d692014-05-20 11:18:06 -07003044 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07003045 mpClientInterface = clientInterface;
3046
Eric Laurent3b73df72014-03-11 09:06:29 -07003047 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
3048 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003049 }
3050
Eric Laurent1afeecb2014-05-14 08:52:28 -07003051 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07003052 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
3053 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
3054 ALOGE("could not load audio policy configuration file, setting defaults");
3055 defaultAudioPolicyConfig();
3056 }
3057 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003058 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003059
3060 // must be done after reading the policy
3061 initializeVolumeCurves();
3062
3063 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003064 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3065 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003066 for (size_t i = 0; i < mHwModules.size(); i++) {
3067 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
3068 if (mHwModules[i]->mHandle == 0) {
3069 ALOGW("could not open HW module %s", mHwModules[i]->mName);
3070 continue;
3071 }
3072 // open all output streams needed to access attached devices
3073 // except for direct output streams that are only opened when they are actually
3074 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003075 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003076 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3077 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003078 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003079
Eric Laurent3a4311c2014-03-17 12:00:47 -07003080 if (outProfile->mSupportedDevices.isEmpty()) {
3081 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
3082 continue;
3083 }
3084
Eric Laurentd78f1532014-09-16 16:38:20 -07003085 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
3086 continue;
3087 }
Eric Laurent83b88082014-06-20 18:31:16 -07003088 audio_devices_t profileType = outProfile->mSupportedDevices.types();
3089 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
3090 profileType = mDefaultOutputDevice->mDeviceType;
3091 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07003092 // chose first device present in mSupportedDevices also part of
3093 // outputDeviceTypes
3094 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3095 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
3096 if ((profileType & outputDeviceTypes) != 0) {
3097 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003098 }
Eric Laurente552edb2014-03-10 17:42:56 -07003099 }
3100 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003101 if ((profileType & outputDeviceTypes) == 0) {
3102 continue;
3103 }
3104 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
3105
3106 outputDesc->mDevice = profileType;
3107 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3108 config.sample_rate = outputDesc->mSamplingRate;
3109 config.channel_mask = outputDesc->mChannelMask;
3110 config.format = outputDesc->mFormat;
3111 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3112 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
3113 &output,
3114 &config,
3115 &outputDesc->mDevice,
3116 String8(""),
3117 &outputDesc->mLatency,
3118 outputDesc->mFlags);
3119
3120 if (status != NO_ERROR) {
3121 ALOGW("Cannot open output stream for device %08x on hw module %s",
3122 outputDesc->mDevice,
3123 mHwModules[i]->mName);
3124 } else {
3125 outputDesc->mSamplingRate = config.sample_rate;
3126 outputDesc->mChannelMask = config.channel_mask;
3127 outputDesc->mFormat = config.format;
3128
3129 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3130 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
3131 ssize_t index =
3132 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
3133 // give a valid ID to an attached device once confirmed it is reachable
3134 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
3135 mAvailableOutputDevices[index]->mId = nextUniqueId();
3136 mAvailableOutputDevices[index]->mModule = mHwModules[i];
3137 }
3138 }
3139 if (mPrimaryOutput == 0 &&
3140 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
3141 mPrimaryOutput = output;
3142 }
3143 addOutput(output, outputDesc);
3144 setOutputDevice(output,
3145 outputDesc->mDevice,
3146 true);
3147 }
Eric Laurente552edb2014-03-10 17:42:56 -07003148 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003149 // open input streams needed to access attached devices to validate
3150 // mAvailableInputDevices list
3151 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3152 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003153 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003154
Eric Laurent3a4311c2014-03-17 12:00:47 -07003155 if (inProfile->mSupportedDevices.isEmpty()) {
3156 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
3157 continue;
3158 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003159 // chose first device present in mSupportedDevices also part of
3160 // inputDeviceTypes
3161 audio_devices_t profileType = AUDIO_DEVICE_NONE;
3162 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3163 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
3164 if (profileType & inputDeviceTypes) {
3165 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003166 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003167 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003168 if ((profileType & inputDeviceTypes) == 0) {
3169 continue;
3170 }
3171 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
3172
3173 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
3174 inputDesc->mDevice = profileType;
3175
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003176 // find the address
3177 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3178 // the inputs vector must be of size 1, but we don't want to crash here
3179 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3180 : String8("");
3181 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3182 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3183
Eric Laurentd78f1532014-09-16 16:38:20 -07003184 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3185 config.sample_rate = inputDesc->mSamplingRate;
3186 config.channel_mask = inputDesc->mChannelMask;
3187 config.format = inputDesc->mFormat;
3188 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3189 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
3190 &input,
3191 &config,
3192 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003193 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003194 AUDIO_SOURCE_MIC,
3195 AUDIO_INPUT_FLAG_NONE);
3196
3197 if (status == NO_ERROR) {
3198 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3199 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
3200 ssize_t index =
3201 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
3202 // give a valid ID to an attached device once confirmed it is reachable
3203 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
3204 mAvailableInputDevices[index]->mId = nextUniqueId();
3205 mAvailableInputDevices[index]->mModule = mHwModules[i];
3206 }
3207 }
3208 mpClientInterface->closeInput(input);
3209 } else {
3210 ALOGW("Cannot open input stream for device %08x on hw module %s",
3211 inputDesc->mDevice,
3212 mHwModules[i]->mName);
3213 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003214 }
3215 }
3216 // make sure all attached devices have been allocated a unique ID
3217 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
3218 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003219 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003220 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3221 continue;
3222 }
3223 i++;
3224 }
3225 for (size_t i = 0; i < mAvailableInputDevices.size();) {
3226 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003227 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003228 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3229 continue;
3230 }
3231 i++;
3232 }
3233 // make sure default device is reachable
3234 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003235 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003236 }
Eric Laurente552edb2014-03-10 17:42:56 -07003237
3238 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3239
3240 updateDevicesAndOutputs();
3241
3242#ifdef AUDIO_POLICY_TEST
3243 if (mPrimaryOutput != 0) {
3244 AudioParameter outputCmd = AudioParameter();
3245 outputCmd.addInt(String8("set_id"), 0);
3246 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3247
3248 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3249 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003250 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3251 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003252 mTestLatencyMs = 0;
3253 mCurOutput = 0;
3254 mDirectOutput = false;
3255 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3256 mTestOutputs[i] = 0;
3257 }
3258
3259 const size_t SIZE = 256;
3260 char buffer[SIZE];
3261 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3262 run(buffer, ANDROID_PRIORITY_AUDIO);
3263 }
3264#endif //AUDIO_POLICY_TEST
3265}
3266
Eric Laurente0720872014-03-11 09:30:41 -07003267AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003268{
3269#ifdef AUDIO_POLICY_TEST
3270 exit();
3271#endif //AUDIO_POLICY_TEST
3272 for (size_t i = 0; i < mOutputs.size(); i++) {
3273 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003274 }
3275 for (size_t i = 0; i < mInputs.size(); i++) {
3276 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003277 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003278 mAvailableOutputDevices.clear();
3279 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003280 mOutputs.clear();
3281 mInputs.clear();
3282 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003283}
3284
Eric Laurente0720872014-03-11 09:30:41 -07003285status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003286{
3287 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
3288}
3289
3290#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003291bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003292{
3293 ALOGV("entering threadLoop()");
3294 while (!exitPending())
3295 {
3296 String8 command;
3297 int valueInt;
3298 String8 value;
3299
3300 Mutex::Autolock _l(mLock);
3301 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3302
3303 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3304 AudioParameter param = AudioParameter(command);
3305
3306 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3307 valueInt != 0) {
3308 ALOGV("Test command %s received", command.string());
3309 String8 target;
3310 if (param.get(String8("target"), target) != NO_ERROR) {
3311 target = "Manager";
3312 }
3313 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3314 param.remove(String8("test_cmd_policy_output"));
3315 mCurOutput = valueInt;
3316 }
3317 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3318 param.remove(String8("test_cmd_policy_direct"));
3319 if (value == "false") {
3320 mDirectOutput = false;
3321 } else if (value == "true") {
3322 mDirectOutput = true;
3323 }
3324 }
3325 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3326 param.remove(String8("test_cmd_policy_input"));
3327 mTestInput = valueInt;
3328 }
3329
3330 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3331 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003332 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003333 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003334 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003335 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003336 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003337 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003338 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003339 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003340 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003341 if (target == "Manager") {
3342 mTestFormat = format;
3343 } else if (mTestOutputs[mCurOutput] != 0) {
3344 AudioParameter outputParam = AudioParameter();
3345 outputParam.addInt(String8("format"), format);
3346 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3347 }
3348 }
3349 }
3350 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3351 param.remove(String8("test_cmd_policy_channels"));
3352 int channels = 0;
3353
3354 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003355 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003356 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003357 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003358 }
3359 if (channels != 0) {
3360 if (target == "Manager") {
3361 mTestChannels = channels;
3362 } else if (mTestOutputs[mCurOutput] != 0) {
3363 AudioParameter outputParam = AudioParameter();
3364 outputParam.addInt(String8("channels"), channels);
3365 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3366 }
3367 }
3368 }
3369 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3370 param.remove(String8("test_cmd_policy_sampleRate"));
3371 if (valueInt >= 0 && valueInt <= 96000) {
3372 int samplingRate = valueInt;
3373 if (target == "Manager") {
3374 mTestSamplingRate = samplingRate;
3375 } else if (mTestOutputs[mCurOutput] != 0) {
3376 AudioParameter outputParam = AudioParameter();
3377 outputParam.addInt(String8("sampling_rate"), samplingRate);
3378 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3379 }
3380 }
3381 }
3382
3383 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3384 param.remove(String8("test_cmd_policy_reopen"));
3385
Eric Laurent1f2f2232014-06-02 12:01:23 -07003386 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003387 mpClientInterface->closeOutput(mPrimaryOutput);
3388
3389 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3390
Eric Laurente552edb2014-03-10 17:42:56 -07003391 mOutputs.removeItem(mPrimaryOutput);
3392
Eric Laurent1f2f2232014-06-02 12:01:23 -07003393 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003394 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003395 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3396 config.sample_rate = outputDesc->mSamplingRate;
3397 config.channel_mask = outputDesc->mChannelMask;
3398 config.format = outputDesc->mFormat;
3399 status_t status = mpClientInterface->openOutput(moduleHandle,
3400 &mPrimaryOutput,
3401 &config,
3402 &outputDesc->mDevice,
3403 String8(""),
3404 &outputDesc->mLatency,
3405 outputDesc->mFlags);
3406 if (status != NO_ERROR) {
3407 ALOGE("Failed to reopen hardware output stream, "
3408 "samplingRate: %d, format %d, channels %d",
3409 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003410 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003411 outputDesc->mSamplingRate = config.sample_rate;
3412 outputDesc->mChannelMask = config.channel_mask;
3413 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003414 AudioParameter outputCmd = AudioParameter();
3415 outputCmd.addInt(String8("set_id"), 0);
3416 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3417 addOutput(mPrimaryOutput, outputDesc);
3418 }
3419 }
3420
3421
3422 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3423 }
3424 }
3425 return false;
3426}
3427
Eric Laurente0720872014-03-11 09:30:41 -07003428void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003429{
3430 {
3431 AutoMutex _l(mLock);
3432 requestExit();
3433 mWaitWorkCV.signal();
3434 }
3435 requestExitAndWait();
3436}
3437
Eric Laurente0720872014-03-11 09:30:41 -07003438int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003439{
3440 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3441 if (output == mTestOutputs[i]) return i;
3442 }
3443 return 0;
3444}
3445#endif //AUDIO_POLICY_TEST
3446
3447// ---
3448
Eric Laurent1f2f2232014-06-02 12:01:23 -07003449void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003450{
Eric Laurent1c333e22014-05-20 10:48:17 -07003451 outputDesc->mIoHandle = output;
3452 outputDesc->mId = nextUniqueId();
3453 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003454 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003455}
3456
Eric Laurent1f2f2232014-06-02 12:01:23 -07003457void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003458{
Eric Laurent1c333e22014-05-20 10:48:17 -07003459 inputDesc->mIoHandle = input;
3460 inputDesc->mId = nextUniqueId();
3461 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003462 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003463}
Eric Laurente552edb2014-03-10 17:42:56 -07003464
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003465void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003466 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003467 const String8 address /*in*/,
3468 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003469 sp<DeviceDescriptor> devDesc =
3470 desc->mProfile->mSupportedDevices.getDevice(device, address);
3471 if (devDesc != 0) {
3472 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3473 desc->mIoHandle, address.string());
3474 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003475 }
3476}
3477
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003478status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003479 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003480 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003481 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003482{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003483 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003484 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003485 // erase all current sample rates, formats and channel masks
3486 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003487
Eric Laurent3b73df72014-03-11 09:06:29 -07003488 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003489 // first list already open outputs that can be routed to this device
3490 for (size_t i = 0; i < mOutputs.size(); i++) {
3491 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003492 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003493 if (!deviceDistinguishesOnAddress(device)) {
3494 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3495 outputs.add(mOutputs.keyAt(i));
3496 } else {
3497 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003498 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003499 }
Eric Laurente552edb2014-03-10 17:42:56 -07003500 }
3501 }
3502 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003503 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003504 for (size_t i = 0; i < mHwModules.size(); i++)
3505 {
3506 if (mHwModules[i]->mHandle == 0) {
3507 continue;
3508 }
3509 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3510 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003511 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3512 if (profile->mSupportedDevices.types() & device) {
3513 if (!deviceDistinguishesOnAddress(device) ||
3514 address == profile->mSupportedDevices[0]->mAddress) {
3515 profiles.add(profile);
3516 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3517 }
Eric Laurente552edb2014-03-10 17:42:56 -07003518 }
3519 }
3520 }
3521
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003522 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3523
Eric Laurente552edb2014-03-10 17:42:56 -07003524 if (profiles.isEmpty() && outputs.isEmpty()) {
3525 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3526 return BAD_VALUE;
3527 }
3528
3529 // open outputs for matching profiles if needed. Direct outputs are also opened to
3530 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3531 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003532 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003533
3534 // nothing to do if one output is already opened for this profile
3535 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003536 for (j = 0; j < outputs.size(); j++) {
3537 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003538 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003539 // matching profile: save the sample rates, format and channel masks supported
3540 // by the profile in our device descriptor
3541 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003542 break;
3543 }
3544 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003545 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003546 continue;
3547 }
3548
Eric Laurent83b88082014-06-20 18:31:16 -07003549 ALOGV("opening output for device %08x with params %s profile %p",
3550 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003551 desc = new AudioOutputDescriptor(profile);
3552 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003553 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3554 config.sample_rate = desc->mSamplingRate;
3555 config.channel_mask = desc->mChannelMask;
3556 config.format = desc->mFormat;
3557 config.offload_info.sample_rate = desc->mSamplingRate;
3558 config.offload_info.channel_mask = desc->mChannelMask;
3559 config.offload_info.format = desc->mFormat;
3560 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3561 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3562 &output,
3563 &config,
3564 &desc->mDevice,
3565 address,
3566 &desc->mLatency,
3567 desc->mFlags);
3568 if (status == NO_ERROR) {
3569 desc->mSamplingRate = config.sample_rate;
3570 desc->mChannelMask = config.channel_mask;
3571 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003572
Eric Laurentd4692962014-05-05 18:13:44 -07003573 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003574 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003575 char *param = audio_device_address_to_parameter(device, address);
3576 mpClientInterface->setParameters(output, String8(param));
3577 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003578 }
3579
Eric Laurentd4692962014-05-05 18:13:44 -07003580 // Here is where we step through and resolve any "dynamic" fields
3581 String8 reply;
3582 char *value;
3583 if (profile->mSamplingRates[0] == 0) {
3584 reply = mpClientInterface->getParameters(output,
3585 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003586 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003587 reply.string());
3588 value = strpbrk((char *)reply.string(), "=");
3589 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003590 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003591 }
Eric Laurentd4692962014-05-05 18:13:44 -07003592 }
3593 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3594 reply = mpClientInterface->getParameters(output,
3595 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003596 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003597 reply.string());
3598 value = strpbrk((char *)reply.string(), "=");
3599 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003600 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003601 }
Eric Laurentd4692962014-05-05 18:13:44 -07003602 }
3603 if (profile->mChannelMasks[0] == 0) {
3604 reply = mpClientInterface->getParameters(output,
3605 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003606 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003607 reply.string());
3608 value = strpbrk((char *)reply.string(), "=");
3609 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003610 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003611 }
Eric Laurentd4692962014-05-05 18:13:44 -07003612 }
3613 if (((profile->mSamplingRates[0] == 0) &&
3614 (profile->mSamplingRates.size() < 2)) ||
3615 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3616 (profile->mFormats.size() < 2)) ||
3617 ((profile->mChannelMasks[0] == 0) &&
3618 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003619 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003620 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003621 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003622 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3623 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003624 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003625 config.sample_rate = profile->pickSamplingRate();
3626 config.channel_mask = profile->pickChannelMask();
3627 config.format = profile->pickFormat();
3628 config.offload_info.sample_rate = config.sample_rate;
3629 config.offload_info.channel_mask = config.channel_mask;
3630 config.offload_info.format = config.format;
3631 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3632 &output,
3633 &config,
3634 &desc->mDevice,
3635 address,
3636 &desc->mLatency,
3637 desc->mFlags);
3638 if (status == NO_ERROR) {
3639 desc->mSamplingRate = config.sample_rate;
3640 desc->mChannelMask = config.channel_mask;
3641 desc->mFormat = config.format;
3642 } else {
3643 output = AUDIO_IO_HANDLE_NONE;
3644 }
Eric Laurentd4692962014-05-05 18:13:44 -07003645 }
3646
Eric Laurentcf2c0212014-07-25 16:20:43 -07003647 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003648 addOutput(output, desc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003649 if (deviceDistinguishesOnAddress(device) && address != "0") {
3650 ssize_t index = mPolicyMixes.indexOfKey(address);
3651 if (index >= 0) {
3652 mPolicyMixes[index]->mOutput = desc;
Eric Laurentc722f302014-12-10 11:21:49 -08003653 desc->mPolicyMix = &mPolicyMixes[index]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08003654 } else {
3655 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3656 address.string());
3657 }
Eric Laurentc722f302014-12-10 11:21:49 -08003658 } else if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
3659 // no duplicated output for direct outputs and
3660 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003661 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003662
Eric Laurentd4692962014-05-05 18:13:44 -07003663 // set initial stream volume for device
3664 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003665
Eric Laurentd4692962014-05-05 18:13:44 -07003666 //TODO: configure audio effect output stage here
3667
3668 // open a duplicating output thread for the new output and the primary output
3669 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3670 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003671 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003672 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003673 sp<AudioOutputDescriptor> dupOutputDesc =
3674 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003675 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3676 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3677 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3678 dupOutputDesc->mFormat = desc->mFormat;
3679 dupOutputDesc->mChannelMask = desc->mChannelMask;
3680 dupOutputDesc->mLatency = desc->mLatency;
3681 addOutput(duplicatedOutput, dupOutputDesc);
3682 applyStreamVolumes(duplicatedOutput, device, 0, true);
3683 } else {
3684 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3685 mPrimaryOutput, output);
3686 mpClientInterface->closeOutput(output);
3687 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003688 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003689 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003690 }
Eric Laurente552edb2014-03-10 17:42:56 -07003691 }
3692 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003693 } else {
3694 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003695 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003696 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003697 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003698 profiles.removeAt(profile_index);
3699 profile_index--;
3700 } else {
3701 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003702 devDesc->importAudioPort(profile);
3703
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003704 if (deviceDistinguishesOnAddress(device)) {
3705 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3706 device, address.string());
3707 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3708 NULL/*patch handle*/, address.string());
3709 }
Eric Laurente552edb2014-03-10 17:42:56 -07003710 ALOGV("checkOutputsForDevice(): adding output %d", output);
3711 }
3712 }
3713
3714 if (profiles.isEmpty()) {
3715 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3716 return BAD_VALUE;
3717 }
Eric Laurentd4692962014-05-05 18:13:44 -07003718 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003719 // check if one opened output is not needed any more after disconnecting one device
3720 for (size_t i = 0; i < mOutputs.size(); i++) {
3721 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003722 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003723 // exact match on device
3724 if (deviceDistinguishesOnAddress(device) &&
3725 (desc->mProfile->mSupportedDevices.types() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003726 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08003727 } else if (!(desc->mProfile->mSupportedDevices.types()
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003728 & mAvailableOutputDevices.types())) {
3729 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3730 mOutputs.keyAt(i));
3731 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003732 }
Eric Laurente552edb2014-03-10 17:42:56 -07003733 }
3734 }
Eric Laurentd4692962014-05-05 18:13:44 -07003735 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003736 for (size_t i = 0; i < mHwModules.size(); i++)
3737 {
3738 if (mHwModules[i]->mHandle == 0) {
3739 continue;
3740 }
3741 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3742 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003743 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003744 if (profile->mSupportedDevices.types() & device) {
3745 ALOGV("checkOutputsForDevice(): "
3746 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003747 if (profile->mSamplingRates[0] == 0) {
3748 profile->mSamplingRates.clear();
3749 profile->mSamplingRates.add(0);
3750 }
3751 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3752 profile->mFormats.clear();
3753 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3754 }
3755 if (profile->mChannelMasks[0] == 0) {
3756 profile->mChannelMasks.clear();
3757 profile->mChannelMasks.add(0);
3758 }
3759 }
3760 }
3761 }
3762 }
3763 return NO_ERROR;
3764}
3765
Eric Laurentd4692962014-05-05 18:13:44 -07003766status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3767 audio_policy_dev_state_t state,
3768 SortedVector<audio_io_handle_t>& inputs,
3769 const String8 address)
3770{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003771 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003772 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3773 // first list already open inputs that can be routed to this device
3774 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3775 desc = mInputs.valueAt(input_index);
3776 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3777 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3778 inputs.add(mInputs.keyAt(input_index));
3779 }
3780 }
3781
3782 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003783 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003784 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3785 {
3786 if (mHwModules[module_idx]->mHandle == 0) {
3787 continue;
3788 }
3789 for (size_t profile_index = 0;
3790 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3791 profile_index++)
3792 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003793 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3794
3795 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3796 if (!deviceDistinguishesOnAddress(device) ||
3797 address == profile->mSupportedDevices[0]->mAddress) {
3798 profiles.add(profile);
3799 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3800 profile_index, module_idx);
3801 }
Eric Laurentd4692962014-05-05 18:13:44 -07003802 }
3803 }
3804 }
3805
3806 if (profiles.isEmpty() && inputs.isEmpty()) {
3807 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3808 return BAD_VALUE;
3809 }
3810
3811 // open inputs for matching profiles if needed. Direct inputs are also opened to
3812 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3813 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3814
Eric Laurent1c333e22014-05-20 10:48:17 -07003815 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003816 // nothing to do if one input is already opened for this profile
3817 size_t input_index;
3818 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3819 desc = mInputs.valueAt(input_index);
3820 if (desc->mProfile == profile) {
3821 break;
3822 }
3823 }
3824 if (input_index != mInputs.size()) {
3825 continue;
3826 }
3827
3828 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3829 desc = new AudioInputDescriptor(profile);
3830 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003831 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3832 config.sample_rate = desc->mSamplingRate;
3833 config.channel_mask = desc->mChannelMask;
3834 config.format = desc->mFormat;
3835 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3836 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3837 &input,
3838 &config,
3839 &desc->mDevice,
3840 address,
3841 AUDIO_SOURCE_MIC,
3842 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003843
Eric Laurentcf2c0212014-07-25 16:20:43 -07003844 if (status == NO_ERROR) {
3845 desc->mSamplingRate = config.sample_rate;
3846 desc->mChannelMask = config.channel_mask;
3847 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003848
Eric Laurentd4692962014-05-05 18:13:44 -07003849 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003850 char *param = audio_device_address_to_parameter(device, address);
3851 mpClientInterface->setParameters(input, String8(param));
3852 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003853 }
3854
3855 // Here is where we step through and resolve any "dynamic" fields
3856 String8 reply;
3857 char *value;
3858 if (profile->mSamplingRates[0] == 0) {
3859 reply = mpClientInterface->getParameters(input,
3860 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3861 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3862 reply.string());
3863 value = strpbrk((char *)reply.string(), "=");
3864 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003865 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003866 }
3867 }
3868 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3869 reply = mpClientInterface->getParameters(input,
3870 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3871 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3872 value = strpbrk((char *)reply.string(), "=");
3873 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003874 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003875 }
3876 }
3877 if (profile->mChannelMasks[0] == 0) {
3878 reply = mpClientInterface->getParameters(input,
3879 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3880 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3881 reply.string());
3882 value = strpbrk((char *)reply.string(), "=");
3883 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003884 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003885 }
3886 }
3887 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3888 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3889 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3890 ALOGW("checkInputsForDevice() direct input missing param");
3891 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003892 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003893 }
3894
3895 if (input != 0) {
3896 addInput(input, desc);
3897 }
3898 } // endif input != 0
3899
Eric Laurentcf2c0212014-07-25 16:20:43 -07003900 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003901 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003902 profiles.removeAt(profile_index);
3903 profile_index--;
3904 } else {
3905 inputs.add(input);
3906 ALOGV("checkInputsForDevice(): adding input %d", input);
3907 }
3908 } // end scan profiles
3909
3910 if (profiles.isEmpty()) {
3911 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3912 return BAD_VALUE;
3913 }
3914 } else {
3915 // Disconnect
3916 // check if one opened input is not needed any more after disconnecting one device
3917 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3918 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003919 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3920 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003921 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3922 mInputs.keyAt(input_index));
3923 inputs.add(mInputs.keyAt(input_index));
3924 }
3925 }
3926 // Clear any profiles associated with the disconnected device.
3927 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3928 if (mHwModules[module_index]->mHandle == 0) {
3929 continue;
3930 }
3931 for (size_t profile_index = 0;
3932 profile_index < mHwModules[module_index]->mInputProfiles.size();
3933 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003934 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003935 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003936 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003937 profile_index, module_index);
3938 if (profile->mSamplingRates[0] == 0) {
3939 profile->mSamplingRates.clear();
3940 profile->mSamplingRates.add(0);
3941 }
3942 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3943 profile->mFormats.clear();
3944 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3945 }
3946 if (profile->mChannelMasks[0] == 0) {
3947 profile->mChannelMasks.clear();
3948 profile->mChannelMasks.add(0);
3949 }
3950 }
3951 }
3952 }
3953 } // end disconnect
3954
3955 return NO_ERROR;
3956}
3957
3958
Eric Laurente0720872014-03-11 09:30:41 -07003959void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003960{
3961 ALOGV("closeOutput(%d)", output);
3962
Eric Laurent1f2f2232014-06-02 12:01:23 -07003963 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003964 if (outputDesc == NULL) {
3965 ALOGW("closeOutput() unknown output %d", output);
3966 return;
3967 }
3968
Eric Laurent275e8e92014-11-30 15:14:47 -08003969 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
3970 if (mPolicyMixes[i]->mOutput == outputDesc) {
3971 mPolicyMixes[i]->mOutput.clear();
3972 }
3973 }
3974
Eric Laurente552edb2014-03-10 17:42:56 -07003975 // look for duplicated outputs connected to the output being removed.
3976 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003977 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003978 if (dupOutputDesc->isDuplicated() &&
3979 (dupOutputDesc->mOutput1 == outputDesc ||
3980 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003981 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003982 if (dupOutputDesc->mOutput1 == outputDesc) {
3983 outputDesc2 = dupOutputDesc->mOutput2;
3984 } else {
3985 outputDesc2 = dupOutputDesc->mOutput1;
3986 }
3987 // As all active tracks on duplicated output will be deleted,
3988 // and as they were also referenced on the other output, the reference
3989 // count for their stream type must be adjusted accordingly on
3990 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003991 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003992 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003993 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003994 }
3995 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3996 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3997
3998 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003999 mOutputs.removeItem(duplicatedOutput);
4000 }
4001 }
4002
Eric Laurent05b90f82014-08-27 15:32:29 -07004003 nextAudioPortGeneration();
4004
4005 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4006 if (index >= 0) {
4007 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4008 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4009 mAudioPatches.removeItemsAt(index);
4010 mpClientInterface->onAudioPatchListUpdate();
4011 }
4012
Eric Laurente552edb2014-03-10 17:42:56 -07004013 AudioParameter param;
4014 param.add(String8("closing"), String8("true"));
4015 mpClientInterface->setParameters(output, param.toString());
4016
4017 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004018 mOutputs.removeItem(output);
4019 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004020}
4021
4022void AudioPolicyManager::closeInput(audio_io_handle_t input)
4023{
4024 ALOGV("closeInput(%d)", input);
4025
4026 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4027 if (inputDesc == NULL) {
4028 ALOGW("closeInput() unknown input %d", input);
4029 return;
4030 }
4031
Eric Laurent6a94d692014-05-20 11:18:06 -07004032 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004033
4034 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4035 if (index >= 0) {
4036 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4037 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4038 mAudioPatches.removeItemsAt(index);
4039 mpClientInterface->onAudioPatchListUpdate();
4040 }
4041
4042 mpClientInterface->closeInput(input);
4043 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004044}
4045
Eric Laurente0720872014-03-11 09:30:41 -07004046SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07004047 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004048{
4049 SortedVector<audio_io_handle_t> outputs;
4050
4051 ALOGVV("getOutputsForDevice() device %04x", device);
4052 for (size_t i = 0; i < openOutputs.size(); i++) {
4053 ALOGVV("output %d isDuplicated=%d device=%04x",
4054 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
4055 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4056 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4057 outputs.add(openOutputs.keyAt(i));
4058 }
4059 }
4060 return outputs;
4061}
4062
Eric Laurente0720872014-03-11 09:30:41 -07004063bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07004064 SortedVector<audio_io_handle_t>& outputs2)
4065{
4066 if (outputs1.size() != outputs2.size()) {
4067 return false;
4068 }
4069 for (size_t i = 0; i < outputs1.size(); i++) {
4070 if (outputs1[i] != outputs2[i]) {
4071 return false;
4072 }
4073 }
4074 return true;
4075}
4076
Eric Laurente0720872014-03-11 09:30:41 -07004077void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004078{
4079 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4080 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4081 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4082 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4083
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004084 // also take into account external policy-related changes: add all outputs which are
4085 // associated with policies in the "before" and "after" output vectors
4086 ALOGVV("checkOutputForStrategy(): policy related outputs");
4087 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
4088 const sp<AudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
4089 if (desc != 0 && desc->mPolicyMix != NULL) {
4090 srcOutputs.add(desc->mIoHandle);
4091 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4092 }
4093 }
4094 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
4095 const sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4096 if (desc != 0 && desc->mPolicyMix != NULL) {
4097 dstOutputs.add(desc->mIoHandle);
4098 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4099 }
4100 }
4101
Eric Laurente552edb2014-03-10 17:42:56 -07004102 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4103 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4104 strategy, srcOutputs[0], dstOutputs[0]);
4105 // mute strategy while moving tracks from one output to another
4106 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004107 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004108 if (desc->isStrategyActive(strategy)) {
4109 setStrategyMute(strategy, true, srcOutputs[i]);
4110 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
4111 }
4112 }
4113
4114 // Move effects associated to this strategy from previous output to new output
4115 if (strategy == STRATEGY_MEDIA) {
4116 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4117 SortedVector<audio_io_handle_t> moved;
4118 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004119 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4120 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4121 effectDesc->mIo != fxOutput) {
4122 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004123 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4124 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004125 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004126 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004127 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004128 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004129 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004130 }
4131 }
4132 }
4133 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004134 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004135 if (i == AUDIO_STREAM_PATCH) {
4136 continue;
4137 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004138 if (getStrategy((audio_stream_type_t)i) == strategy) {
4139 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004140 }
4141 }
4142 }
4143}
4144
Eric Laurente0720872014-03-11 09:30:41 -07004145void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004146{
Jon Eklund966095e2014-09-09 15:39:49 -05004147 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4148 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004149 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05004150 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4151 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004152 checkOutputForStrategy(STRATEGY_SONIFICATION);
4153 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004154 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004155 checkOutputForStrategy(STRATEGY_MEDIA);
4156 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004157 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004158}
4159
Eric Laurente0720872014-03-11 09:30:41 -07004160audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07004161{
Eric Laurente552edb2014-03-10 17:42:56 -07004162 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004163 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004164 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
4165 return mOutputs.keyAt(i);
4166 }
4167 }
4168
4169 return 0;
4170}
4171
Eric Laurente0720872014-03-11 09:30:41 -07004172void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004173{
Eric Laurente552edb2014-03-10 17:42:56 -07004174 audio_io_handle_t a2dpOutput = getA2dpOutput();
4175 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004176 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004177 return;
4178 }
4179
Eric Laurent3a4311c2014-03-17 12:00:47 -07004180 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004181 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4182 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4183 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004184 // suspend A2DP output if:
4185 // (NOT already suspended) &&
4186 // ((SCO device is connected &&
4187 // (forced usage for communication || for record is SCO))) ||
4188 // (phone state is ringing || in call)
4189 //
4190 // restore A2DP output if:
4191 // (Already suspended) &&
4192 // ((SCO device is NOT connected ||
4193 // (forced usage NOT for communication && NOT for record is SCO))) &&
4194 // (phone state is NOT ringing && NOT in call)
4195 //
4196 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004197 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004198 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
4199 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
4200 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
4201 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004202
4203 mpClientInterface->restoreOutput(a2dpOutput);
4204 mA2dpSuspended = false;
4205 }
4206 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004207 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004208 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4209 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
4210 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
4211 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004212
4213 mpClientInterface->suspendOutput(a2dpOutput);
4214 mA2dpSuspended = true;
4215 }
4216 }
4217}
4218
Eric Laurent1c333e22014-05-20 10:48:17 -07004219audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004220{
4221 audio_devices_t device = AUDIO_DEVICE_NONE;
4222
Eric Laurent1f2f2232014-06-02 12:01:23 -07004223 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004224
4225 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4226 if (index >= 0) {
4227 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4228 if (patchDesc->mUid != mUidCached) {
4229 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4230 outputDesc->device(), outputDesc->mPatchHandle);
4231 return outputDesc->device();
4232 }
4233 }
4234
Eric Laurente552edb2014-03-10 17:42:56 -07004235 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004236 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004237 // use device for strategy enforced audible
4238 // 2: we are in call or the strategy phone is active on the output:
4239 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004240 // 3: the strategy for enforced audible is active but not enforced on the output:
4241 // use the device for strategy enforced audible
4242 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004243 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05004244 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004245 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004246 // 6: the strategy accessibility is active on the output:
4247 // use device for strategy accessibility
4248 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004249 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004250 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004251 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004252 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004253 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05004254 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
4255 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004256 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4257 } else if (isInCall() ||
4258 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
4259 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05004260 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
4261 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004262 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
4263 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
4264 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
4265 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004266 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
4267 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004268 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
4269 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
4270 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
4271 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004272 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
4273 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004274 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
4275 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004276 }
4277
Eric Laurent1c333e22014-05-20 10:48:17 -07004278 ALOGV("getNewOutputDevice() selected device %x", device);
4279 return device;
4280}
4281
4282audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4283{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004284 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004285
4286 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4287 if (index >= 0) {
4288 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4289 if (patchDesc->mUid != mUidCached) {
4290 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4291 inputDesc->mDevice, inputDesc->mPatchHandle);
4292 return inputDesc->mDevice;
4293 }
4294 }
4295
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004296 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07004297
4298 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004299 return device;
4300}
4301
Eric Laurente0720872014-03-11 09:30:41 -07004302uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004303 return (uint32_t)getStrategy(stream);
4304}
4305
Eric Laurente0720872014-03-11 09:30:41 -07004306audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004307 // By checking the range of stream before calling getStrategy, we avoid
4308 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4309 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004310 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004311 return AUDIO_DEVICE_NONE;
4312 }
4313 audio_devices_t devices;
4314 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
4315 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4316 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4317 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004318 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07004319 if (outputDesc->isStrategyActive(strategy)) {
4320 devices = outputDesc->device();
4321 break;
4322 }
Eric Laurente552edb2014-03-10 17:42:56 -07004323 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004324
4325 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4326 and doesn't really need to.*/
4327 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4328 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4329 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4330 }
4331
Eric Laurente552edb2014-03-10 17:42:56 -07004332 return devices;
4333}
4334
Eric Laurente0720872014-03-11 09:30:41 -07004335AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004336 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004337
4338 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4339
Eric Laurente552edb2014-03-10 17:42:56 -07004340 // stream to strategy mapping
4341 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004342 case AUDIO_STREAM_VOICE_CALL:
4343 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004344 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004345 case AUDIO_STREAM_RING:
4346 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004347 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004348 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004349 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004350 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004351 return STRATEGY_DTMF;
4352 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004353 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004354 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004355 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4356 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004357 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004358 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004359 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004360 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004361 case AUDIO_STREAM_TTS:
4362 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004363 case AUDIO_STREAM_ACCESSIBILITY:
4364 return STRATEGY_ACCESSIBILITY;
4365 case AUDIO_STREAM_REROUTING:
4366 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004367 }
4368}
4369
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004370uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4371 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004372 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4373 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4374 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004375 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4376 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4377 }
4378
4379 // usage to strategy mapping
4380 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004381 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4382 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4383 return (uint32_t) STRATEGY_SONIFICATION;
4384 }
4385 if (isInCall()) {
4386 return (uint32_t) STRATEGY_PHONE;
4387 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004388 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004389
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004390 case AUDIO_USAGE_MEDIA:
4391 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004392 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4393 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4394 return (uint32_t) STRATEGY_MEDIA;
4395
4396 case AUDIO_USAGE_VOICE_COMMUNICATION:
4397 return (uint32_t) STRATEGY_PHONE;
4398
4399 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4400 return (uint32_t) STRATEGY_DTMF;
4401
4402 case AUDIO_USAGE_ALARM:
4403 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4404 return (uint32_t) STRATEGY_SONIFICATION;
4405
4406 case AUDIO_USAGE_NOTIFICATION:
4407 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4408 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4409 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4410 case AUDIO_USAGE_NOTIFICATION_EVENT:
4411 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4412
4413 case AUDIO_USAGE_UNKNOWN:
4414 default:
4415 return (uint32_t) STRATEGY_MEDIA;
4416 }
4417}
4418
Eric Laurente0720872014-03-11 09:30:41 -07004419void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004420 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004421 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004422 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4423 updateDevicesAndOutputs();
4424 break;
4425 default:
4426 break;
4427 }
4428}
4429
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004430bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4431 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4432 if (s == (size_t) streamToIgnore) {
4433 continue;
4434 }
4435 for (size_t i = 0; i < mOutputs.size(); i++) {
4436 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4437 if (outputDesc->mRefCount[s] != 0) {
4438 return true;
4439 }
4440 }
4441 }
4442 return false;
4443}
4444
4445uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4446 switch(event) {
4447 case STARTING_OUTPUT:
4448 mBeaconMuteRefCount++;
4449 break;
4450 case STOPPING_OUTPUT:
4451 if (mBeaconMuteRefCount > 0) {
4452 mBeaconMuteRefCount--;
4453 }
4454 break;
4455 case STARTING_BEACON:
4456 mBeaconPlayingRefCount++;
4457 break;
4458 case STOPPING_BEACON:
4459 if (mBeaconPlayingRefCount > 0) {
4460 mBeaconPlayingRefCount--;
4461 }
4462 break;
4463 }
4464
4465 if (mBeaconMuteRefCount > 0) {
4466 // any playback causes beacon to be muted
4467 return setBeaconMute(true);
4468 } else {
4469 // no other playback: unmute when beacon starts playing, mute when it stops
4470 return setBeaconMute(mBeaconPlayingRefCount == 0);
4471 }
4472}
4473
4474uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4475 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4476 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4477 // keep track of muted state to avoid repeating mute/unmute operations
4478 if (mBeaconMuted != mute) {
4479 // mute/unmute AUDIO_STREAM_TTS on all outputs
4480 ALOGV("\t muting %d", mute);
4481 uint32_t maxLatency = 0;
4482 for (size_t i = 0; i < mOutputs.size(); i++) {
4483 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4484 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4485 desc->mIoHandle,
4486 0 /*delay*/, AUDIO_DEVICE_NONE);
4487 const uint32_t latency = desc->latency() * 2;
4488 if (latency > maxLatency) {
4489 maxLatency = latency;
4490 }
4491 }
4492 mBeaconMuted = mute;
4493 return maxLatency;
4494 }
4495 return 0;
4496}
4497
Eric Laurente0720872014-03-11 09:30:41 -07004498audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004499 bool fromCache)
4500{
4501 uint32_t device = AUDIO_DEVICE_NONE;
4502
4503 if (fromCache) {
4504 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4505 strategy, mDeviceForStrategy[strategy]);
4506 return mDeviceForStrategy[strategy];
4507 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004508 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004509 switch (strategy) {
4510
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004511 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4512 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4513 if (!device) {
4514 ALOGE("getDeviceForStrategy() no device found for "\
4515 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4516 }
4517 break;
4518
Eric Laurente552edb2014-03-10 17:42:56 -07004519 case STRATEGY_SONIFICATION_RESPECTFUL:
4520 if (isInCall()) {
4521 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004522 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004523 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4524 // while media is playing on a remote device, use the the sonification behavior.
4525 // Note that we test this usecase before testing if media is playing because
4526 // the isStreamActive() method only informs about the activity of a stream, not
4527 // if it's for local playback. Note also that we use the same delay between both tests
4528 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004529 //user "safe" speaker if available instead of normal speaker to avoid triggering
4530 //other acoustic safety mechanisms for notification
4531 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4532 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004533 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004534 // while media is playing (or has recently played), use the same device
4535 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4536 } else {
4537 // when media is not playing anymore, fall back on the sonification behavior
4538 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004539 //user "safe" speaker if available instead of normal speaker to avoid triggering
4540 //other acoustic safety mechanisms for notification
4541 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4542 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004543 }
4544
4545 break;
4546
4547 case STRATEGY_DTMF:
4548 if (!isInCall()) {
4549 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4550 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4551 break;
4552 }
4553 // when in call, DTMF and PHONE strategies follow the same rules
4554 // FALL THROUGH
4555
4556 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004557 // Force use of only devices on primary output if:
4558 // - in call AND
4559 // - cannot route from voice call RX OR
4560 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4561 if (mPhoneState == AUDIO_MODE_IN_CALL) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004562 audio_devices_t txDevice =
4563 getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -07004564 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4565 if (((mAvailableInputDevices.types() &
4566 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4567 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004568 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004569 AUDIO_DEVICE_API_VERSION_3_0))) {
4570 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4571 }
4572 }
Eric Laurente552edb2014-03-10 17:42:56 -07004573 // for phone strategy, we first consider the forced use and then the available devices by order
4574 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004575 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4576 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004577 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004578 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004579 if (device) break;
4580 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004581 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004582 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004583 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004584 if (device) break;
4585 // if SCO device is requested but no SCO device is available, fall back to default case
4586 // FALL THROUGH
4587
4588 default: // FORCE_NONE
4589 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004590 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004591 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004592 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004593 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004594 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004595 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004596 if (device) break;
4597 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004598 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004599 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004600 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004601 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004602 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4603 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004604 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004605 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004606 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004607 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004608 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004609 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004610 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004611 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004612 if (device) break;
4613 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004614 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004615 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004616 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004617 if (device == AUDIO_DEVICE_NONE) {
4618 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4619 }
4620 break;
4621
Eric Laurent3b73df72014-03-11 09:06:29 -07004622 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004623 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4624 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004625 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004626 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004627 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004628 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004629 if (device) break;
4630 }
Eric Laurentcd71a692014-12-16 12:01:12 -08004631 if (!isInCall()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004632 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004633 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004634 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004635 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004636 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004637 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004638 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004639 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004640 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004641 if (device) break;
4642 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004643 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4644 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004645 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004646 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004647 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004648 if (device == AUDIO_DEVICE_NONE) {
4649 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4650 }
4651 break;
4652 }
4653 break;
4654
4655 case STRATEGY_SONIFICATION:
4656
4657 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4658 // handleIncallSonification().
4659 if (isInCall()) {
4660 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4661 break;
4662 }
4663 // FALL THROUGH
4664
4665 case STRATEGY_ENFORCED_AUDIBLE:
4666 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4667 // except:
4668 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4669 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4670
4671 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004672 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004673 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004674 if (device == AUDIO_DEVICE_NONE) {
4675 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4676 }
4677 }
4678 // The second device used for sonification is the same as the device used by media strategy
4679 // FALL THROUGH
4680
Eric Laurent223fd5c2014-11-11 13:43:36 -08004681 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4682 case STRATEGY_ACCESSIBILITY:
Eric Laurent066ceec2014-11-25 12:35:01 -08004683 if (strategy == STRATEGY_ACCESSIBILITY) {
4684 // do not route accessibility prompts to a digital output currently configured with a
4685 // compressed format as they would likely not be mixed and dropped.
4686 for (size_t i = 0; i < mOutputs.size(); i++) {
4687 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4688 audio_devices_t devices = desc->device() &
4689 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4690 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4691 devices != AUDIO_DEVICE_NONE) {
4692 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4693 }
4694 }
4695 }
4696 // FALL THROUGH
4697
Eric Laurent223fd5c2014-11-11 13:43:36 -08004698 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004699 case STRATEGY_MEDIA: {
4700 uint32_t device2 = AUDIO_DEVICE_NONE;
4701 if (strategy != STRATEGY_SONIFICATION) {
4702 // no sonification on remote submix (e.g. WFD)
Eric Laurent275e8e92014-11-30 15:14:47 -08004703 if (mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, String8("0")) != 0) {
4704 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
4705 }
Eric Laurente552edb2014-03-10 17:42:56 -07004706 }
4707 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004708 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004709 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004710 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004711 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004712 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004713 }
4714 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004715 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004716 }
4717 }
Hochi Huang327cb702014-09-21 09:47:31 +08004718 if ((device2 == AUDIO_DEVICE_NONE) &&
4719 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4720 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4721 }
Eric Laurente552edb2014-03-10 17:42:56 -07004722 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004723 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004724 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004725 if ((device2 == AUDIO_DEVICE_NONE)) {
4726 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4727 }
Eric Laurente552edb2014-03-10 17:42:56 -07004728 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004729 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004730 }
4731 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004732 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004733 }
4734 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004735 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004736 }
4737 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004738 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004739 }
4740 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4741 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004742 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004743 }
4744 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004745 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004746 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004747 }
4748 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004749 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004750 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004751 int device3 = AUDIO_DEVICE_NONE;
4752 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004753 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004754 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4755 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004756 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004757 }
Eric Laurente552edb2014-03-10 17:42:56 -07004758
Jungshik Jang839e4f32014-06-26 17:23:40 +09004759 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004760 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4761 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4762 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004763
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004764 // If hdmi system audio mode is on, remove speaker out of output list.
4765 if ((strategy == STRATEGY_MEDIA) &&
4766 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4767 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4768 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4769 }
4770
Eric Laurente552edb2014-03-10 17:42:56 -07004771 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004772 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004773 if (device == AUDIO_DEVICE_NONE) {
4774 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4775 }
4776 } break;
4777
4778 default:
4779 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4780 break;
4781 }
4782
4783 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4784 return device;
4785}
4786
Eric Laurente0720872014-03-11 09:30:41 -07004787void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004788{
4789 for (int i = 0; i < NUM_STRATEGIES; i++) {
4790 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4791 }
4792 mPreviousOutputs = mOutputs;
4793}
4794
Eric Laurent1f2f2232014-06-02 12:01:23 -07004795uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004796 audio_devices_t prevDevice,
4797 uint32_t delayMs)
4798{
4799 // mute/unmute strategies using an incompatible device combination
4800 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4801 // if unmuting, unmute only after the specified delay
4802 if (outputDesc->isDuplicated()) {
4803 return 0;
4804 }
4805
4806 uint32_t muteWaitMs = 0;
4807 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004808 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004809
4810 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4811 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004812 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004813 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4814 bool doMute = false;
4815
4816 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4817 doMute = true;
4818 outputDesc->mStrategyMutedByDevice[i] = true;
4819 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4820 doMute = true;
4821 outputDesc->mStrategyMutedByDevice[i] = false;
4822 }
Eric Laurent99401132014-05-07 19:48:15 -07004823 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004824 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004825 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004826 // skip output if it does not share any device with current output
4827 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4828 == AUDIO_DEVICE_NONE) {
4829 continue;
4830 }
4831 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4832 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4833 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4834 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4835 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004836 if (mute) {
4837 // FIXME: should not need to double latency if volume could be applied
4838 // immediately by the audioflinger mixer. We must account for the delay
4839 // between now and the next time the audioflinger thread for this output
4840 // will process a buffer (which corresponds to one buffer size,
4841 // usually 1/2 or 1/4 of the latency).
4842 if (muteWaitMs < desc->latency() * 2) {
4843 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004844 }
4845 }
4846 }
4847 }
4848 }
4849 }
4850
Eric Laurent99401132014-05-07 19:48:15 -07004851 // temporary mute output if device selection changes to avoid volume bursts due to
4852 // different per device volumes
4853 if (outputDesc->isActive() && (device != prevDevice)) {
4854 if (muteWaitMs < outputDesc->latency() * 2) {
4855 muteWaitMs = outputDesc->latency() * 2;
4856 }
4857 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4858 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004859 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004860 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004861 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004862 muteWaitMs *2, device);
4863 }
4864 }
4865 }
4866
Eric Laurente552edb2014-03-10 17:42:56 -07004867 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4868 if (muteWaitMs > delayMs) {
4869 muteWaitMs -= delayMs;
4870 usleep(muteWaitMs * 1000);
4871 return muteWaitMs;
4872 }
4873 return 0;
4874}
4875
Eric Laurente0720872014-03-11 09:30:41 -07004876uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004877 audio_devices_t device,
4878 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004879 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004880 audio_patch_handle_t *patchHandle,
4881 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004882{
4883 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004884 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004885 AudioParameter param;
4886 uint32_t muteWaitMs;
4887
4888 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004889 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4890 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004891 return muteWaitMs;
4892 }
4893 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4894 // output profile
4895 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004896 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004897 return 0;
4898 }
4899
4900 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004901 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004902
4903 audio_devices_t prevDevice = outputDesc->mDevice;
4904
4905 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4906
4907 if (device != AUDIO_DEVICE_NONE) {
4908 outputDesc->mDevice = device;
4909 }
4910 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4911
4912 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004913 // the requested device is AUDIO_DEVICE_NONE
4914 // OR the requested device is the same as current device
4915 // AND force is not specified
4916 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004917 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004918 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4919 outputDesc->mPatchHandle != 0) {
4920 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4921 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004922 return muteWaitMs;
4923 }
4924
4925 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004926
Eric Laurente552edb2014-03-10 17:42:56 -07004927 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004928 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004929 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004930 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004931 DeviceVector deviceList = (address == NULL) ?
4932 mAvailableOutputDevices.getDevicesFromType(device)
4933 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004934 if (!deviceList.isEmpty()) {
4935 struct audio_patch patch;
4936 outputDesc->toAudioPortConfig(&patch.sources[0]);
4937 patch.num_sources = 1;
4938 patch.num_sinks = 0;
4939 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4940 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004941 patch.num_sinks++;
4942 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004943 ssize_t index;
4944 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4945 index = mAudioPatches.indexOfKey(*patchHandle);
4946 } else {
4947 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4948 }
4949 sp< AudioPatch> patchDesc;
4950 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4951 if (index >= 0) {
4952 patchDesc = mAudioPatches.valueAt(index);
4953 afPatchHandle = patchDesc->mAfPatchHandle;
4954 }
4955
Eric Laurent1c333e22014-05-20 10:48:17 -07004956 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004957 &afPatchHandle,
4958 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004959 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4960 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004961 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004962 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004963 if (index < 0) {
4964 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4965 &patch, mUidCached);
4966 addAudioPatch(patchDesc->mHandle, patchDesc);
4967 } else {
4968 patchDesc->mPatch = patch;
4969 }
4970 patchDesc->mAfPatchHandle = afPatchHandle;
4971 patchDesc->mUid = mUidCached;
4972 if (patchHandle) {
4973 *patchHandle = patchDesc->mHandle;
4974 }
4975 outputDesc->mPatchHandle = patchDesc->mHandle;
4976 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004977 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004978 }
4979 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004980
4981 // inform all input as well
4982 for (size_t i = 0; i < mInputs.size(); i++) {
4983 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4984 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4985 AudioParameter inputCmd = AudioParameter();
4986 ALOGV("%s: inform input %d of device:%d", __func__,
4987 inputDescriptor->mIoHandle, device);
4988 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4989 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4990 inputCmd.toString(),
4991 delayMs);
4992 }
4993 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004994 }
Eric Laurente552edb2014-03-10 17:42:56 -07004995
4996 // update stream volumes according to new device
4997 applyStreamVolumes(output, device, delayMs);
4998
4999 return muteWaitMs;
5000}
5001
Eric Laurent1c333e22014-05-20 10:48:17 -07005002status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07005003 int delayMs,
5004 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005005{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005006 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07005007 ssize_t index;
5008 if (patchHandle) {
5009 index = mAudioPatches.indexOfKey(*patchHandle);
5010 } else {
5011 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
5012 }
5013 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005014 return INVALID_OPERATION;
5015 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005016 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5017 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005018 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
5019 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005020 removeAudioPatch(patchDesc->mHandle);
5021 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005022 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005023 return status;
5024}
5025
5026status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5027 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005028 bool force,
5029 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005030{
5031 status_t status = NO_ERROR;
5032
Eric Laurent1f2f2232014-06-02 12:01:23 -07005033 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005034 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5035 inputDesc->mDevice = device;
5036
5037 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5038 if (!deviceList.isEmpty()) {
5039 struct audio_patch patch;
5040 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005041 // AUDIO_SOURCE_HOTWORD is for internal use only:
5042 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005043 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
5044 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005045 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5046 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005047 patch.num_sinks = 1;
5048 //only one input device for now
5049 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005050 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005051 ssize_t index;
5052 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5053 index = mAudioPatches.indexOfKey(*patchHandle);
5054 } else {
5055 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5056 }
5057 sp< AudioPatch> patchDesc;
5058 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5059 if (index >= 0) {
5060 patchDesc = mAudioPatches.valueAt(index);
5061 afPatchHandle = patchDesc->mAfPatchHandle;
5062 }
5063
Eric Laurent1c333e22014-05-20 10:48:17 -07005064 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005065 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005066 0);
5067 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005068 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005069 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005070 if (index < 0) {
5071 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
5072 &patch, mUidCached);
5073 addAudioPatch(patchDesc->mHandle, patchDesc);
5074 } else {
5075 patchDesc->mPatch = patch;
5076 }
5077 patchDesc->mAfPatchHandle = afPatchHandle;
5078 patchDesc->mUid = mUidCached;
5079 if (patchHandle) {
5080 *patchHandle = patchDesc->mHandle;
5081 }
5082 inputDesc->mPatchHandle = patchDesc->mHandle;
5083 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005084 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005085 }
5086 }
5087 }
5088 return status;
5089}
5090
Eric Laurent6a94d692014-05-20 11:18:06 -07005091status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5092 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005093{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005094 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005095 ssize_t index;
5096 if (patchHandle) {
5097 index = mAudioPatches.indexOfKey(*patchHandle);
5098 } else {
5099 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5100 }
5101 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005102 return INVALID_OPERATION;
5103 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005104 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5105 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005106 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
5107 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005108 removeAudioPatch(patchDesc->mHandle);
5109 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005110 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005111 return status;
5112}
5113
5114sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08005115 String8 address,
Glenn Kastencbd48022014-07-24 13:46:44 -07005116 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07005117 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005118 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07005119 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005120{
5121 // Choose an input profile based on the requested capture parameters: select the first available
5122 // profile supporting all requested parameters.
5123
5124 for (size_t i = 0; i < mHwModules.size(); i++)
5125 {
5126 if (mHwModules[i]->mHandle == 0) {
5127 continue;
5128 }
5129 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5130 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005131 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005132 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005133 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005134 &samplingRate /*updatedSamplingRate*/,
5135 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005136
Eric Laurente552edb2014-03-10 17:42:56 -07005137 return profile;
5138 }
5139 }
5140 }
5141 return NULL;
5142}
5143
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005144
5145audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
Eric Laurentc722f302014-12-10 11:21:49 -08005146 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005147{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005148 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5149 ~AUDIO_DEVICE_BIT_IN;
Eric Laurent275e8e92014-11-30 15:14:47 -08005150
5151 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
5152 if (mPolicyMixes[i]->mMix.mMixType != MIX_TYPE_RECORDERS) {
5153 continue;
5154 }
5155 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
5156 if ((RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5157 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource == inputSource) ||
5158 (RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5159 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource != inputSource)) {
5160 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurentc722f302014-12-10 11:21:49 -08005161 if (policyMix != NULL) {
5162 *policyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005163 }
5164 return AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5165 }
5166 break;
5167 }
5168 }
5169 }
5170
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005171 return getDeviceForInputSource(inputSource);
5172}
5173
5174audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5175{
5176 uint32_t device = AUDIO_DEVICE_NONE;
5177 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5178 ~AUDIO_DEVICE_BIT_IN;
5179
Eric Laurente552edb2014-03-10 17:42:56 -07005180 switch (inputSource) {
5181 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005182 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005183 device = AUDIO_DEVICE_IN_VOICE_CALL;
5184 break;
5185 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005186 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005187
5188 case AUDIO_SOURCE_DEFAULT:
5189 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07005190 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
5191 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentdc136ff2014-12-16 12:24:18 -08005192 } else if ((mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO) &&
5193 (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET)) {
5194 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurentc2730ba2014-07-20 15:47:07 -07005195 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5196 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5197 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5198 device = AUDIO_DEVICE_IN_USB_DEVICE;
5199 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5200 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005201 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005202 break;
5203
5204 case AUDIO_SOURCE_VOICE_COMMUNICATION:
5205 // Allow only use of devices on primary input if in call and HAL does not support routing
5206 // to voice call path.
5207 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
5208 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
5209 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
5210 }
5211
5212 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
5213 case AUDIO_POLICY_FORCE_BT_SCO:
5214 // if SCO device is requested but no SCO device is available, fall back to default case
5215 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
5216 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
5217 break;
5218 }
5219 // FALL THROUGH
5220
5221 default: // FORCE_NONE
5222 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5223 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5224 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5225 device = AUDIO_DEVICE_IN_USB_DEVICE;
5226 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5227 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5228 }
5229 break;
5230
5231 case AUDIO_POLICY_FORCE_SPEAKER:
5232 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
5233 device = AUDIO_DEVICE_IN_BACK_MIC;
5234 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5235 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5236 }
5237 break;
5238 }
5239 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005240
Eric Laurente552edb2014-03-10 17:42:56 -07005241 case AUDIO_SOURCE_VOICE_RECOGNITION:
5242 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07005243 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005244 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005245 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005246 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005247 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07005248 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5249 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005250 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005251 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5252 }
5253 break;
5254 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005255 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005256 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005257 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005258 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5259 }
5260 break;
5261 case AUDIO_SOURCE_VOICE_DOWNLINK:
5262 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005263 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005264 device = AUDIO_DEVICE_IN_VOICE_CALL;
5265 }
5266 break;
5267 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005268 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07005269 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5270 }
5271 break;
Hochi Huang327cb702014-09-21 09:47:31 +08005272 case AUDIO_SOURCE_FM_TUNER:
5273 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
5274 device = AUDIO_DEVICE_IN_FM_TUNER;
5275 }
5276 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005277 default:
5278 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
5279 break;
5280 }
5281 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
5282 return device;
5283}
5284
Eric Laurente0720872014-03-11 09:30:41 -07005285bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005286{
5287 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
5288 device &= ~AUDIO_DEVICE_BIT_IN;
5289 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
5290 return true;
5291 }
5292 return false;
5293}
5294
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005295bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005296 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL & ~AUDIO_DEVICE_BIT_IN) != 0);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005297}
5298
Eric Laurente0720872014-03-11 09:30:41 -07005299audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005300{
5301 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005302 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07005303 if ((input_descriptor->mRefCount > 0)
5304 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
5305 return mInputs.keyAt(i);
5306 }
5307 }
5308 return 0;
5309}
5310
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005311uint32_t AudioPolicyManager::activeInputsCount() const
5312{
5313 uint32_t count = 0;
5314 for (size_t i = 0; i < mInputs.size(); i++) {
5315 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
5316 if (desc->mRefCount > 0) {
Eric Laurenta34c9ce2014-12-19 11:16:32 -08005317 count++;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005318 }
5319 }
5320 return count;
5321}
5322
Eric Laurente552edb2014-03-10 17:42:56 -07005323
Eric Laurente0720872014-03-11 09:30:41 -07005324audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005325{
5326 if (device == AUDIO_DEVICE_NONE) {
5327 // this happens when forcing a route update and no track is active on an output.
5328 // In this case the returned category is not important.
5329 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07005330 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07005331 // Multiple device selection is either:
5332 // - speaker + one other device: give priority to speaker in this case.
5333 // - one A2DP device + another device: happens with duplicated output. In this case
5334 // retain the device on the A2DP output as the other must not correspond to an active
5335 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09005336 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07005337 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
5338 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09005339 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
5340 device = AUDIO_DEVICE_OUT_HDMI_ARC;
5341 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
5342 device = AUDIO_DEVICE_OUT_AUX_LINE;
5343 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
5344 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07005345 } else {
5346 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
5347 }
5348 }
5349
Jon Eklund11c9fb12014-06-23 14:47:03 -05005350 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
5351 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
5352 device = AUDIO_DEVICE_OUT_SPEAKER;
5353
Eric Laurent3b73df72014-03-11 09:06:29 -07005354 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07005355 "getDeviceForVolume() invalid device combination: %08x",
5356 device);
5357
5358 return device;
5359}
5360
Eric Laurente0720872014-03-11 09:30:41 -07005361AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005362{
5363 switch(getDeviceForVolume(device)) {
5364 case AUDIO_DEVICE_OUT_EARPIECE:
5365 return DEVICE_CATEGORY_EARPIECE;
5366 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5367 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5368 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5369 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5370 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5371 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5372 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05005373 case AUDIO_DEVICE_OUT_LINE:
5374 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5375 /*USB? Remote submix?*/
5376 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07005377 case AUDIO_DEVICE_OUT_SPEAKER:
5378 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5379 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005380 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5381 case AUDIO_DEVICE_OUT_USB_DEVICE:
5382 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5383 default:
5384 return DEVICE_CATEGORY_SPEAKER;
5385 }
5386}
5387
Eric Laurent223fd5c2014-11-11 13:43:36 -08005388/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005389float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005390 int indexInUi)
5391{
5392 device_category deviceCategory = getDeviceCategory(device);
5393 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5394
5395 // the volume index in the UI is relative to the min and max volume indices for this stream type
5396 int nbSteps = 1 + curve[VOLMAX].mIndex -
5397 curve[VOLMIN].mIndex;
5398 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5399 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5400
5401 // find what part of the curve this index volume belongs to, or if it's out of bounds
5402 int segment = 0;
5403 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5404 return 0.0f;
5405 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5406 segment = 0;
5407 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5408 segment = 1;
5409 } else if (volIdx <= curve[VOLMAX].mIndex) {
5410 segment = 2;
5411 } else { // out of bounds
5412 return 1.0f;
5413 }
5414
5415 // linear interpolation in the attenuation table in dB
5416 float decibels = curve[segment].mDBAttenuation +
5417 ((float)(volIdx - curve[segment].mIndex)) *
5418 ( (curve[segment+1].mDBAttenuation -
5419 curve[segment].mDBAttenuation) /
5420 ((float)(curve[segment+1].mIndex -
5421 curve[segment].mIndex)) );
5422
5423 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5424
5425 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5426 curve[segment].mIndex, volIdx,
5427 curve[segment+1].mIndex,
5428 curve[segment].mDBAttenuation,
5429 decibels,
5430 curve[segment+1].mDBAttenuation,
5431 amplification);
5432
5433 return amplification;
5434}
5435
Eric Laurente0720872014-03-11 09:30:41 -07005436const AudioPolicyManager::VolumeCurvePoint
5437 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005438 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5439};
5440
Eric Laurente0720872014-03-11 09:30:41 -07005441const AudioPolicyManager::VolumeCurvePoint
5442 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005443 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5444};
5445
Eric Laurente0720872014-03-11 09:30:41 -07005446const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005447 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5448 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5449};
5450
5451const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005452 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005453 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5454};
5455
Eric Laurente0720872014-03-11 09:30:41 -07005456const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005457 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005458 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005459};
5460
5461const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005462 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005463 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5464};
5465
Eric Laurente0720872014-03-11 09:30:41 -07005466const AudioPolicyManager::VolumeCurvePoint
5467 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005468 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5469};
5470
5471// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5472// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5473// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5474// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5475
Eric Laurente0720872014-03-11 09:30:41 -07005476const AudioPolicyManager::VolumeCurvePoint
5477 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005478 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5479};
5480
Eric Laurente0720872014-03-11 09:30:41 -07005481const AudioPolicyManager::VolumeCurvePoint
5482 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005483 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5484};
5485
Eric Laurente0720872014-03-11 09:30:41 -07005486const AudioPolicyManager::VolumeCurvePoint
5487 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005488 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5489};
5490
Eric Laurente0720872014-03-11 09:30:41 -07005491const AudioPolicyManager::VolumeCurvePoint
5492 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005493 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5494};
5495
Eric Laurente0720872014-03-11 09:30:41 -07005496const AudioPolicyManager::VolumeCurvePoint
5497 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005498 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5499};
5500
Eric Laurente0720872014-03-11 09:30:41 -07005501const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005502 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5503 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5504};
5505
5506const AudioPolicyManager::VolumeCurvePoint
5507 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5508 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5509};
5510
5511const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005512 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5513 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5514};
5515
5516const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005517 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5518 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005519 { // AUDIO_STREAM_VOICE_CALL
5520 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5521 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005522 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5523 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005524 },
5525 { // AUDIO_STREAM_SYSTEM
5526 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5527 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005528 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5529 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005530 },
5531 { // AUDIO_STREAM_RING
5532 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5533 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005534 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5535 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005536 },
5537 { // AUDIO_STREAM_MUSIC
5538 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5539 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005540 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5541 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005542 },
5543 { // AUDIO_STREAM_ALARM
5544 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5545 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005546 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5547 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005548 },
5549 { // AUDIO_STREAM_NOTIFICATION
5550 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5551 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005552 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5553 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005554 },
5555 { // AUDIO_STREAM_BLUETOOTH_SCO
5556 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5557 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005558 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5559 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005560 },
5561 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5562 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5563 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005564 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5565 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005566 },
5567 { // AUDIO_STREAM_DTMF
5568 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5569 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005570 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5571 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005572 },
5573 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005574 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5575 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5576 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5577 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5578 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005579 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005580 { // AUDIO_STREAM_ACCESSIBILITY
5581 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5582 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5583 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5584 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5585 },
5586 { // AUDIO_STREAM_REROUTING
5587 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5588 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5589 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5590 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5591 },
5592 { // AUDIO_STREAM_PATCH
5593 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5594 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5595 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5596 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5597 },
Eric Laurente552edb2014-03-10 17:42:56 -07005598};
5599
Eric Laurente0720872014-03-11 09:30:41 -07005600void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005601{
5602 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5603 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5604 mStreams[i].mVolumeCurve[j] =
5605 sVolumeProfiles[i][j];
5606 }
5607 }
5608
5609 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5610 if (mSpeakerDrcEnabled) {
5611 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5612 sDefaultSystemVolumeCurveDrc;
5613 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5614 sSpeakerSonificationVolumeCurveDrc;
5615 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5616 sSpeakerSonificationVolumeCurveDrc;
5617 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5618 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005619 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5620 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005621 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5622 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005623 }
5624}
5625
Eric Laurente0720872014-03-11 09:30:41 -07005626float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005627 int index,
5628 audio_io_handle_t output,
5629 audio_devices_t device)
5630{
5631 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005632 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005633 StreamDescriptor &streamDesc = mStreams[stream];
5634
5635 if (device == AUDIO_DEVICE_NONE) {
5636 device = outputDesc->device();
5637 }
5638
Eric Laurente552edb2014-03-10 17:42:56 -07005639 volume = volIndexToAmpl(device, streamDesc, index);
5640
5641 // if a headset is connected, apply the following rules to ring tones and notifications
5642 // to avoid sound level bursts in user's ears:
5643 // - always attenuate ring tones and notifications volume by 6dB
5644 // - if music is playing, always limit the volume to current music volume,
5645 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005646 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005647 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5648 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5649 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5650 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5651 ((stream_strategy == STRATEGY_SONIFICATION)
5652 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005653 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005654 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005655 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005656 streamDesc.mCanBeMuted) {
5657 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5658 // when the phone is ringing we must consider that music could have been paused just before
5659 // by the music application and behave as if music was active if the last music track was
5660 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005661 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005662 mLimitRingtoneVolume) {
5663 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005664 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5665 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005666 output,
5667 musicDevice);
5668 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5669 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5670 if (volume > minVol) {
5671 volume = minVol;
5672 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5673 }
5674 }
5675 }
5676
5677 return volume;
5678}
5679
Eric Laurente0720872014-03-11 09:30:41 -07005680status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005681 int index,
5682 audio_io_handle_t output,
5683 audio_devices_t device,
5684 int delayMs,
5685 bool force)
5686{
5687
5688 // do not change actual stream volume if the stream is muted
5689 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5690 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5691 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5692 return NO_ERROR;
5693 }
5694
5695 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005696 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5697 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5698 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5699 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005700 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005701 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005702 return INVALID_OPERATION;
5703 }
5704
5705 float volume = computeVolume(stream, index, output, device);
Eric Laurent275e8e92014-11-30 15:14:47 -08005706 // unit gain if rerouting to external policy
5707 if (device == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
5708 ssize_t index = mOutputs.indexOfKey(output);
5709 if (index >= 0) {
5710 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurentc722f302014-12-10 11:21:49 -08005711 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005712 ALOGV("max gain when rerouting for output=%d", output);
5713 volume = 1.0f;
5714 }
5715 }
5716
5717 }
Eric Laurente552edb2014-03-10 17:42:56 -07005718 // We actually change the volume if:
5719 // - the float value returned by computeVolume() changed
5720 // - the force flag is set
5721 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5722 force) {
5723 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5724 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5725 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5726 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005727 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5728 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005729 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005730 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005731 }
5732
Eric Laurent3b73df72014-03-11 09:06:29 -07005733 if (stream == AUDIO_STREAM_VOICE_CALL ||
5734 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005735 float voiceVolume;
5736 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005737 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005738 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5739 } else {
5740 voiceVolume = 1.0;
5741 }
5742
5743 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5744 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5745 mLastVoiceVolume = voiceVolume;
5746 }
5747 }
5748
5749 return NO_ERROR;
5750}
5751
Eric Laurente0720872014-03-11 09:30:41 -07005752void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005753 audio_devices_t device,
5754 int delayMs,
5755 bool force)
5756{
5757 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5758
Eric Laurent3b73df72014-03-11 09:06:29 -07005759 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005760 if (stream == AUDIO_STREAM_PATCH) {
5761 continue;
5762 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005763 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005764 mStreams[stream].getVolumeIndex(device),
5765 output,
5766 device,
5767 delayMs,
5768 force);
5769 }
5770}
5771
Eric Laurente0720872014-03-11 09:30:41 -07005772void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005773 bool on,
5774 audio_io_handle_t output,
5775 int delayMs,
5776 audio_devices_t device)
5777{
5778 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005779 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005780 if (stream == AUDIO_STREAM_PATCH) {
5781 continue;
5782 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005783 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5784 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005785 }
5786 }
5787}
5788
Eric Laurente0720872014-03-11 09:30:41 -07005789void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005790 bool on,
5791 audio_io_handle_t output,
5792 int delayMs,
5793 audio_devices_t device)
5794{
5795 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005796 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005797 if (device == AUDIO_DEVICE_NONE) {
5798 device = outputDesc->device();
5799 }
5800
5801 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5802 stream, on, output, outputDesc->mMuteCount[stream], device);
5803
5804 if (on) {
5805 if (outputDesc->mMuteCount[stream] == 0) {
5806 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005807 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5808 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005809 checkAndSetVolume(stream, 0, output, device, delayMs);
5810 }
5811 }
5812 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5813 outputDesc->mMuteCount[stream]++;
5814 } else {
5815 if (outputDesc->mMuteCount[stream] == 0) {
5816 ALOGV("setStreamMute() unmuting non muted stream!");
5817 return;
5818 }
5819 if (--outputDesc->mMuteCount[stream] == 0) {
5820 checkAndSetVolume(stream,
5821 streamDesc.getVolumeIndex(device),
5822 output,
5823 device,
5824 delayMs);
5825 }
5826 }
5827}
5828
Eric Laurente0720872014-03-11 09:30:41 -07005829void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005830 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005831{
5832 // if the stream pertains to sonification strategy and we are in call we must
5833 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5834 // in the device used for phone strategy and play the tone if the selected device does not
5835 // interfere with the device used for phone strategy
5836 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5837 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005838 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005839 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5840 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005841 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005842 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5843 stream, starting, outputDesc->mDevice, stateChange);
5844 if (outputDesc->mRefCount[stream]) {
5845 int muteCount = 1;
5846 if (stateChange) {
5847 muteCount = outputDesc->mRefCount[stream];
5848 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005849 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005850 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5851 for (int i = 0; i < muteCount; i++) {
5852 setStreamMute(stream, starting, mPrimaryOutput);
5853 }
5854 } else {
5855 ALOGV("handleIncallSonification() high visibility");
5856 if (outputDesc->device() &
5857 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5858 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5859 for (int i = 0; i < muteCount; i++) {
5860 setStreamMute(stream, starting, mPrimaryOutput);
5861 }
5862 }
5863 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005864 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5865 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005866 } else {
5867 mpClientInterface->stopTone();
5868 }
5869 }
5870 }
5871 }
5872}
5873
Eric Laurente0720872014-03-11 09:30:41 -07005874bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005875{
5876 return isStateInCall(mPhoneState);
5877}
5878
Eric Laurente0720872014-03-11 09:30:41 -07005879bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005880 return ((state == AUDIO_MODE_IN_CALL) ||
5881 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005882}
5883
Eric Laurente0720872014-03-11 09:30:41 -07005884uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005885{
5886 return MAX_EFFECTS_CPU_LOAD;
5887}
5888
Eric Laurente0720872014-03-11 09:30:41 -07005889uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005890{
5891 return MAX_EFFECTS_MEMORY;
5892}
5893
Eric Laurent6a94d692014-05-20 11:18:06 -07005894
Eric Laurente552edb2014-03-10 17:42:56 -07005895// --- AudioOutputDescriptor class implementation
5896
Eric Laurente0720872014-03-11 09:30:41 -07005897AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005898 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005899 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurentc722f302014-12-10 11:21:49 -08005900 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL),
Eric Laurent275e8e92014-11-30 15:14:47 -08005901 mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005902 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5903{
5904 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005905 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005906 mRefCount[i] = 0;
5907 mCurVolume[i] = -1.0;
5908 mMuteCount[i] = 0;
5909 mStopTime[i] = 0;
5910 }
5911 for (int i = 0; i < NUM_STRATEGIES; i++) {
5912 mStrategyMutedByDevice[i] = false;
5913 }
5914 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005915 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005916 mSamplingRate = profile->pickSamplingRate();
5917 mFormat = profile->pickFormat();
5918 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005919 if (profile->mGains.size() > 0) {
5920 profile->mGains[0]->getDefaultConfig(&mGain);
5921 }
Eric Laurente552edb2014-03-10 17:42:56 -07005922 }
5923}
5924
Eric Laurente0720872014-03-11 09:30:41 -07005925audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005926{
5927 if (isDuplicated()) {
5928 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5929 } else {
5930 return mDevice;
5931 }
5932}
5933
Eric Laurente0720872014-03-11 09:30:41 -07005934uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005935{
5936 if (isDuplicated()) {
5937 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5938 } else {
5939 return mLatency;
5940 }
5941}
5942
Eric Laurente0720872014-03-11 09:30:41 -07005943bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005944 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005945{
5946 if (isDuplicated()) {
5947 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5948 } else if (outputDesc->isDuplicated()){
5949 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5950 } else {
5951 return (mProfile->mModule == outputDesc->mProfile->mModule);
5952 }
5953}
5954
Eric Laurente0720872014-03-11 09:30:41 -07005955void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005956 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005957{
5958 // forward usage count change to attached outputs
5959 if (isDuplicated()) {
5960 mOutput1->changeRefCount(stream, delta);
5961 mOutput2->changeRefCount(stream, delta);
5962 }
5963 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005964 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5965 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005966 mRefCount[stream] = 0;
5967 return;
5968 }
5969 mRefCount[stream] += delta;
5970 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5971}
5972
Eric Laurente0720872014-03-11 09:30:41 -07005973audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005974{
5975 if (isDuplicated()) {
5976 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5977 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005978 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005979 }
5980}
5981
Eric Laurente0720872014-03-11 09:30:41 -07005982bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005983{
5984 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5985}
5986
Eric Laurente0720872014-03-11 09:30:41 -07005987bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005988 uint32_t inPastMs,
5989 nsecs_t sysTime) const
5990{
5991 if ((sysTime == 0) && (inPastMs != 0)) {
5992 sysTime = systemTime();
5993 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005994 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005995 if (i == AUDIO_STREAM_PATCH) {
5996 continue;
5997 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005998 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005999 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07006000 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006001 return true;
6002 }
6003 }
6004 return false;
6005}
6006
Eric Laurente0720872014-03-11 09:30:41 -07006007bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07006008 uint32_t inPastMs,
6009 nsecs_t sysTime) const
6010{
6011 if (mRefCount[stream] != 0) {
6012 return true;
6013 }
6014 if (inPastMs == 0) {
6015 return false;
6016 }
6017 if (sysTime == 0) {
6018 sysTime = systemTime();
6019 }
6020 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
6021 return true;
6022 }
6023 return false;
6024}
6025
Eric Laurent1c333e22014-05-20 10:48:17 -07006026void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006027 struct audio_port_config *dstConfig,
6028 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006029{
Eric Laurent84c70242014-06-23 08:46:27 -07006030 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
6031
Eric Laurent1f2f2232014-06-02 12:01:23 -07006032 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6033 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6034 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006035 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006036 }
6037 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6038
Eric Laurent6a94d692014-05-20 11:18:06 -07006039 dstConfig->id = mId;
6040 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
6041 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07006042 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6043 dstConfig->ext.mix.handle = mIoHandle;
6044 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07006045}
6046
6047void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
6048 struct audio_port *port) const
6049{
Eric Laurent84c70242014-06-23 08:46:27 -07006050 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07006051 mProfile->toAudioPort(port);
6052 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006053 toAudioPortConfig(&port->active_config);
6054 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006055 port->ext.mix.handle = mIoHandle;
6056 port->ext.mix.latency_class =
6057 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
6058}
Eric Laurente552edb2014-03-10 17:42:56 -07006059
Eric Laurente0720872014-03-11 09:30:41 -07006060status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006061{
6062 const size_t SIZE = 256;
6063 char buffer[SIZE];
6064 String8 result;
6065
Eric Laurent4d416952014-08-10 14:07:09 -07006066 snprintf(buffer, SIZE, " ID: %d\n", mId);
6067 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006068 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6069 result.append(buffer);
6070 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
6071 result.append(buffer);
6072 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6073 result.append(buffer);
6074 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
6075 result.append(buffer);
6076 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
6077 result.append(buffer);
6078 snprintf(buffer, SIZE, " Devices %08x\n", device());
6079 result.append(buffer);
6080 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
6081 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07006082 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
6083 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
6084 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07006085 result.append(buffer);
6086 }
6087 write(fd, result.string(), result.size());
6088
6089 return NO_ERROR;
6090}
6091
6092// --- AudioInputDescriptor class implementation
6093
Eric Laurent1c333e22014-05-20 10:48:17 -07006094AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006095 : mId(0), mIoHandle(0),
Eric Laurentc722f302014-12-10 11:21:49 -08006096 mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006097 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07006098{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006099 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006100 mSamplingRate = profile->pickSamplingRate();
6101 mFormat = profile->pickFormat();
6102 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07006103 if (profile->mGains.size() > 0) {
6104 profile->mGains[0]->getDefaultConfig(&mGain);
6105 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006106 }
Eric Laurente552edb2014-03-10 17:42:56 -07006107}
6108
Eric Laurent1c333e22014-05-20 10:48:17 -07006109void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006110 struct audio_port_config *dstConfig,
6111 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006112{
Eric Laurent84c70242014-06-23 08:46:27 -07006113 ALOG_ASSERT(mProfile != 0,
6114 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07006115 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6116 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6117 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006118 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006119 }
6120
6121 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6122
Eric Laurent6a94d692014-05-20 11:18:06 -07006123 dstConfig->id = mId;
6124 dstConfig->role = AUDIO_PORT_ROLE_SINK;
6125 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07006126 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6127 dstConfig->ext.mix.handle = mIoHandle;
6128 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07006129}
6130
6131void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
6132 struct audio_port *port) const
6133{
Eric Laurent84c70242014-06-23 08:46:27 -07006134 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
6135
Eric Laurent1c333e22014-05-20 10:48:17 -07006136 mProfile->toAudioPort(port);
6137 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006138 toAudioPortConfig(&port->active_config);
6139 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006140 port->ext.mix.handle = mIoHandle;
6141 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
6142}
6143
Eric Laurente0720872014-03-11 09:30:41 -07006144status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006145{
6146 const size_t SIZE = 256;
6147 char buffer[SIZE];
6148 String8 result;
6149
Eric Laurent4d416952014-08-10 14:07:09 -07006150 snprintf(buffer, SIZE, " ID: %d\n", mId);
6151 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006152 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6153 result.append(buffer);
6154 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
6155 result.append(buffer);
6156 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6157 result.append(buffer);
6158 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
6159 result.append(buffer);
6160 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
6161 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07006162 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
6163 result.append(buffer);
6164
Eric Laurente552edb2014-03-10 17:42:56 -07006165 write(fd, result.string(), result.size());
6166
6167 return NO_ERROR;
6168}
6169
6170// --- StreamDescriptor class implementation
6171
Eric Laurente0720872014-03-11 09:30:41 -07006172AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07006173 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
6174{
6175 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
6176}
6177
Eric Laurente0720872014-03-11 09:30:41 -07006178int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07006179{
Eric Laurente0720872014-03-11 09:30:41 -07006180 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07006181 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
6182 if (mIndexCur.indexOfKey(device) < 0) {
6183 device = AUDIO_DEVICE_OUT_DEFAULT;
6184 }
6185 return mIndexCur.valueFor(device);
6186}
6187
Eric Laurente0720872014-03-11 09:30:41 -07006188void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006189{
6190 const size_t SIZE = 256;
6191 char buffer[SIZE];
6192 String8 result;
6193
6194 snprintf(buffer, SIZE, "%s %02d %02d ",
6195 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
6196 result.append(buffer);
6197 for (size_t i = 0; i < mIndexCur.size(); i++) {
6198 snprintf(buffer, SIZE, "%04x : %02d, ",
6199 mIndexCur.keyAt(i),
6200 mIndexCur.valueAt(i));
6201 result.append(buffer);
6202 }
6203 result.append("\n");
6204
6205 write(fd, result.string(), result.size());
6206}
6207
6208// --- EffectDescriptor class implementation
6209
Eric Laurente0720872014-03-11 09:30:41 -07006210status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006211{
6212 const size_t SIZE = 256;
6213 char buffer[SIZE];
6214 String8 result;
6215
6216 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
6217 result.append(buffer);
6218 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
6219 result.append(buffer);
6220 snprintf(buffer, SIZE, " Session: %d\n", mSession);
6221 result.append(buffer);
6222 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
6223 result.append(buffer);
6224 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
6225 result.append(buffer);
6226 write(fd, result.string(), result.size());
6227
6228 return NO_ERROR;
6229}
6230
Eric Laurent1c333e22014-05-20 10:48:17 -07006231// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006232
Eric Laurente0720872014-03-11 09:30:41 -07006233AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07006234 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
6235 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07006236{
6237}
6238
Eric Laurente0720872014-03-11 09:30:41 -07006239AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07006240{
6241 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006242 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006243 }
6244 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006245 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006246 }
6247 free((void *)mName);
6248}
6249
Eric Laurent1afeecb2014-05-14 08:52:28 -07006250status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
6251{
6252 cnode *node = root->first_child;
6253
6254 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
6255
6256 while (node) {
6257 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6258 profile->loadSamplingRates((char *)node->value);
6259 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6260 profile->loadFormats((char *)node->value);
6261 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6262 profile->loadInChannels((char *)node->value);
6263 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6264 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6265 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07006266 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
6267 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006268 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6269 profile->loadGains(node);
6270 }
6271 node = node->next;
6272 }
6273 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6274 "loadInput() invalid supported devices");
6275 ALOGW_IF(profile->mChannelMasks.size() == 0,
6276 "loadInput() invalid supported channel masks");
6277 ALOGW_IF(profile->mSamplingRates.size() == 0,
6278 "loadInput() invalid supported sampling rates");
6279 ALOGW_IF(profile->mFormats.size() == 0,
6280 "loadInput() invalid supported formats");
6281 if (!profile->mSupportedDevices.isEmpty() &&
6282 (profile->mChannelMasks.size() != 0) &&
6283 (profile->mSamplingRates.size() != 0) &&
6284 (profile->mFormats.size() != 0)) {
6285
6286 ALOGV("loadInput() adding input Supported Devices %04x",
6287 profile->mSupportedDevices.types());
6288
6289 mInputProfiles.add(profile);
6290 return NO_ERROR;
6291 } else {
6292 return BAD_VALUE;
6293 }
6294}
6295
6296status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
6297{
6298 cnode *node = root->first_child;
6299
6300 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
6301
6302 while (node) {
6303 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6304 profile->loadSamplingRates((char *)node->value);
6305 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6306 profile->loadFormats((char *)node->value);
6307 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6308 profile->loadOutChannels((char *)node->value);
6309 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6310 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6311 mDeclaredDevices);
6312 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07006313 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006314 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6315 profile->loadGains(node);
6316 }
6317 node = node->next;
6318 }
6319 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6320 "loadOutput() invalid supported devices");
6321 ALOGW_IF(profile->mChannelMasks.size() == 0,
6322 "loadOutput() invalid supported channel masks");
6323 ALOGW_IF(profile->mSamplingRates.size() == 0,
6324 "loadOutput() invalid supported sampling rates");
6325 ALOGW_IF(profile->mFormats.size() == 0,
6326 "loadOutput() invalid supported formats");
6327 if (!profile->mSupportedDevices.isEmpty() &&
6328 (profile->mChannelMasks.size() != 0) &&
6329 (profile->mSamplingRates.size() != 0) &&
6330 (profile->mFormats.size() != 0)) {
6331
6332 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
6333 profile->mSupportedDevices.types(), profile->mFlags);
6334
6335 mOutputProfiles.add(profile);
6336 return NO_ERROR;
6337 } else {
6338 return BAD_VALUE;
6339 }
6340}
6341
6342status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
6343{
6344 cnode *node = root->first_child;
6345
6346 audio_devices_t type = AUDIO_DEVICE_NONE;
6347 while (node) {
6348 if (strcmp(node->name, DEVICE_TYPE) == 0) {
6349 type = parseDeviceNames((char *)node->value);
6350 break;
6351 }
6352 node = node->next;
6353 }
6354 if (type == AUDIO_DEVICE_NONE ||
6355 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
6356 ALOGW("loadDevice() bad type %08x", type);
6357 return BAD_VALUE;
6358 }
6359 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
6360 deviceDesc->mModule = this;
6361
6362 node = root->first_child;
6363 while (node) {
6364 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
6365 deviceDesc->mAddress = String8((char *)node->value);
6366 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6367 if (audio_is_input_device(type)) {
6368 deviceDesc->loadInChannels((char *)node->value);
6369 } else {
6370 deviceDesc->loadOutChannels((char *)node->value);
6371 }
6372 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6373 deviceDesc->loadGains(node);
6374 }
6375 node = node->next;
6376 }
6377
6378 ALOGV("loadDevice() adding device name %s type %08x address %s",
6379 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6380
6381 mDeclaredDevices.add(deviceDesc);
6382
6383 return NO_ERROR;
6384}
6385
Eric Laurent275e8e92014-11-30 15:14:47 -08006386status_t AudioPolicyManager::HwModule::addOutputProfile(String8 name, const audio_config_t *config,
6387 audio_devices_t device, String8 address)
6388{
6389 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SOURCE, this);
6390
6391 profile->mSamplingRates.add(config->sample_rate);
6392 profile->mChannelMasks.add(config->channel_mask);
6393 profile->mFormats.add(config->format);
6394
6395 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6396 devDesc->mAddress = address;
6397 profile->mSupportedDevices.add(devDesc);
6398
6399 mOutputProfiles.add(profile);
6400
6401 return NO_ERROR;
6402}
6403
6404status_t AudioPolicyManager::HwModule::removeOutputProfile(String8 name)
6405{
6406 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
6407 if (mOutputProfiles[i]->mName == name) {
6408 mOutputProfiles.removeAt(i);
6409 break;
6410 }
6411 }
6412
6413 return NO_ERROR;
6414}
6415
6416status_t AudioPolicyManager::HwModule::addInputProfile(String8 name, const audio_config_t *config,
6417 audio_devices_t device, String8 address)
6418{
6419 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SINK, this);
6420
6421 profile->mSamplingRates.add(config->sample_rate);
6422 profile->mChannelMasks.add(config->channel_mask);
6423 profile->mFormats.add(config->format);
6424
6425 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6426 devDesc->mAddress = address;
6427 profile->mSupportedDevices.add(devDesc);
6428
6429 ALOGV("addInputProfile() name %s rate %d mask 0x08", name.string(), config->sample_rate, config->channel_mask);
6430
6431 mInputProfiles.add(profile);
6432
6433 return NO_ERROR;
6434}
6435
6436status_t AudioPolicyManager::HwModule::removeInputProfile(String8 name)
6437{
6438 for (size_t i = 0; i < mInputProfiles.size(); i++) {
6439 if (mInputProfiles[i]->mName == name) {
6440 mInputProfiles.removeAt(i);
6441 break;
6442 }
6443 }
6444
6445 return NO_ERROR;
6446}
6447
6448
Eric Laurente0720872014-03-11 09:30:41 -07006449void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006450{
6451 const size_t SIZE = 256;
6452 char buffer[SIZE];
6453 String8 result;
6454
6455 snprintf(buffer, SIZE, " - name: %s\n", mName);
6456 result.append(buffer);
6457 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6458 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006459 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6460 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006461 write(fd, result.string(), result.size());
6462 if (mOutputProfiles.size()) {
6463 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6464 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006465 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006466 write(fd, buffer, strlen(buffer));
6467 mOutputProfiles[i]->dump(fd);
6468 }
6469 }
6470 if (mInputProfiles.size()) {
6471 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6472 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006473 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006474 write(fd, buffer, strlen(buffer));
6475 mInputProfiles[i]->dump(fd);
6476 }
6477 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006478 if (mDeclaredDevices.size()) {
6479 write(fd, " - devices:\n", strlen(" - devices:\n"));
6480 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6481 mDeclaredDevices[i]->dump(fd, 4, i);
6482 }
6483 }
Eric Laurente552edb2014-03-10 17:42:56 -07006484}
6485
Eric Laurent1c333e22014-05-20 10:48:17 -07006486// --- AudioPort class implementation
6487
Eric Laurenta121f902014-06-03 13:32:54 -07006488
6489AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6490 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07006491 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006492{
6493 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6494 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6495}
6496
Eric Laurent1c333e22014-05-20 10:48:17 -07006497void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6498{
6499 port->role = mRole;
6500 port->type = mType;
6501 unsigned int i;
6502 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006503 if (mSamplingRates[i] != 0) {
6504 port->sample_rates[i] = mSamplingRates[i];
6505 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006506 }
6507 port->num_sample_rates = i;
6508 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006509 if (mChannelMasks[i] != 0) {
6510 port->channel_masks[i] = mChannelMasks[i];
6511 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006512 }
6513 port->num_channel_masks = i;
6514 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006515 if (mFormats[i] != 0) {
6516 port->formats[i] = mFormats[i];
6517 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006518 }
6519 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006520
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006521 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006522
6523 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6524 port->gains[i] = mGains[i]->mGain;
6525 }
6526 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006527}
6528
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006529void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6530 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6531 const uint32_t rate = port->mSamplingRates.itemAt(k);
6532 if (rate != 0) { // skip "dynamic" rates
6533 bool hasRate = false;
6534 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6535 if (rate == mSamplingRates.itemAt(l)) {
6536 hasRate = true;
6537 break;
6538 }
6539 }
6540 if (!hasRate) { // never import a sampling rate twice
6541 mSamplingRates.add(rate);
6542 }
6543 }
6544 }
6545 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6546 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6547 if (mask != 0) { // skip "dynamic" masks
6548 bool hasMask = false;
6549 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6550 if (mask == mChannelMasks.itemAt(l)) {
6551 hasMask = true;
6552 break;
6553 }
6554 }
6555 if (!hasMask) { // never import a channel mask twice
6556 mChannelMasks.add(mask);
6557 }
6558 }
6559 }
6560 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6561 const audio_format_t format = port->mFormats.itemAt(k);
6562 if (format != 0) { // skip "dynamic" formats
6563 bool hasFormat = false;
6564 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6565 if (format == mFormats.itemAt(l)) {
6566 hasFormat = true;
6567 break;
6568 }
6569 }
6570 if (!hasFormat) { // never import a channel mask twice
6571 mFormats.add(format);
6572 }
6573 }
6574 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006575 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6576 sp<AudioGain> gain = port->mGains.itemAt(k);
6577 if (gain != 0) {
6578 bool hasGain = false;
6579 for (size_t l = 0 ; l < mGains.size() ; l++) {
6580 if (gain == mGains.itemAt(l)) {
6581 hasGain = true;
6582 break;
6583 }
6584 }
6585 if (!hasGain) { // never import a gain twice
6586 mGains.add(gain);
6587 }
6588 }
6589 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006590}
6591
6592void AudioPolicyManager::AudioPort::clearCapabilities() {
6593 mChannelMasks.clear();
6594 mFormats.clear();
6595 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006596 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006597}
Eric Laurent1c333e22014-05-20 10:48:17 -07006598
6599void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6600{
6601 char *str = strtok(name, "|");
6602
6603 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6604 // rates should be read from the output stream after it is opened for the first time
6605 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6606 mSamplingRates.add(0);
6607 return;
6608 }
6609
6610 while (str != NULL) {
6611 uint32_t rate = atoi(str);
6612 if (rate != 0) {
6613 ALOGV("loadSamplingRates() adding rate %d", rate);
6614 mSamplingRates.add(rate);
6615 }
6616 str = strtok(NULL, "|");
6617 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006618}
6619
6620void AudioPolicyManager::AudioPort::loadFormats(char *name)
6621{
6622 char *str = strtok(name, "|");
6623
6624 // by convention, "0' in the first entry in mFormats indicates the supported formats
6625 // should be read from the output stream after it is opened for the first time
6626 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6627 mFormats.add(AUDIO_FORMAT_DEFAULT);
6628 return;
6629 }
6630
6631 while (str != NULL) {
6632 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6633 ARRAY_SIZE(sFormatNameToEnumTable),
6634 str);
6635 if (format != AUDIO_FORMAT_DEFAULT) {
6636 mFormats.add(format);
6637 }
6638 str = strtok(NULL, "|");
6639 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006640}
6641
6642void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6643{
6644 const char *str = strtok(name, "|");
6645
6646 ALOGV("loadInChannels() %s", name);
6647
6648 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6649 mChannelMasks.add(0);
6650 return;
6651 }
6652
6653 while (str != NULL) {
6654 audio_channel_mask_t channelMask =
6655 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6656 ARRAY_SIZE(sInChannelsNameToEnumTable),
6657 str);
6658 if (channelMask != 0) {
6659 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6660 mChannelMasks.add(channelMask);
6661 }
6662 str = strtok(NULL, "|");
6663 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006664}
6665
6666void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6667{
6668 const char *str = strtok(name, "|");
6669
6670 ALOGV("loadOutChannels() %s", name);
6671
6672 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6673 // masks should be read from the output stream after it is opened for the first time
6674 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6675 mChannelMasks.add(0);
6676 return;
6677 }
6678
6679 while (str != NULL) {
6680 audio_channel_mask_t channelMask =
6681 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6682 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6683 str);
6684 if (channelMask != 0) {
6685 mChannelMasks.add(channelMask);
6686 }
6687 str = strtok(NULL, "|");
6688 }
6689 return;
6690}
6691
Eric Laurent1afeecb2014-05-14 08:52:28 -07006692audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6693{
6694 const char *str = strtok(name, "|");
6695
6696 ALOGV("loadGainMode() %s", name);
6697 audio_gain_mode_t mode = 0;
6698 while (str != NULL) {
6699 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6700 ARRAY_SIZE(sGainModeNameToEnumTable),
6701 str);
6702 str = strtok(NULL, "|");
6703 }
6704 return mode;
6705}
6706
Eric Laurenta121f902014-06-03 13:32:54 -07006707void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006708{
6709 cnode *node = root->first_child;
6710
Eric Laurenta121f902014-06-03 13:32:54 -07006711 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006712
6713 while (node) {
6714 if (strcmp(node->name, GAIN_MODE) == 0) {
6715 gain->mGain.mode = loadGainMode((char *)node->value);
6716 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006717 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006718 gain->mGain.channel_mask =
6719 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6720 ARRAY_SIZE(sInChannelsNameToEnumTable),
6721 (char *)node->value);
6722 } else {
6723 gain->mGain.channel_mask =
6724 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6725 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6726 (char *)node->value);
6727 }
6728 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6729 gain->mGain.min_value = atoi((char *)node->value);
6730 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6731 gain->mGain.max_value = atoi((char *)node->value);
6732 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6733 gain->mGain.default_value = atoi((char *)node->value);
6734 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6735 gain->mGain.step_value = atoi((char *)node->value);
6736 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6737 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6738 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6739 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6740 }
6741 node = node->next;
6742 }
6743
6744 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6745 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6746
6747 if (gain->mGain.mode == 0) {
6748 return;
6749 }
6750 mGains.add(gain);
6751}
6752
6753void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6754{
6755 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006756 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006757 while (node) {
6758 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006759 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006760 node = node->next;
6761 }
6762}
6763
Glenn Kastencbd48022014-07-24 13:46:44 -07006764status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006765{
Eric Laurent0daea392014-12-04 19:14:54 -08006766 if (mSamplingRates.isEmpty()) {
6767 return NO_ERROR;
6768 }
6769
Eric Laurenta121f902014-06-03 13:32:54 -07006770 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6771 if (mSamplingRates[i] == samplingRate) {
6772 return NO_ERROR;
6773 }
6774 }
6775 return BAD_VALUE;
6776}
6777
Glenn Kastencbd48022014-07-24 13:46:44 -07006778status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6779 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006780{
Eric Laurent0daea392014-12-04 19:14:54 -08006781 if (mSamplingRates.isEmpty()) {
6782 return NO_ERROR;
6783 }
6784
Glenn Kastencbd48022014-07-24 13:46:44 -07006785 // Search for the closest supported sampling rate that is above (preferred)
6786 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6787 // The sampling rates do not need to be sorted in ascending order.
6788 ssize_t maxBelow = -1;
6789 ssize_t minAbove = -1;
6790 uint32_t candidate;
6791 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6792 candidate = mSamplingRates[i];
6793 if (candidate == samplingRate) {
6794 if (updatedSamplingRate != NULL) {
6795 *updatedSamplingRate = candidate;
6796 }
6797 return NO_ERROR;
6798 }
6799 // candidate < desired
6800 if (candidate < samplingRate) {
6801 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6802 maxBelow = i;
6803 }
6804 // candidate > desired
6805 } else {
6806 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6807 minAbove = i;
6808 }
6809 }
6810 }
6811 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6812 // TODO Move these assumptions out.
6813 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6814 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6815 // due to approximation by an int32_t of the
6816 // phase increments
6817 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6818 if (minAbove >= 0) {
6819 candidate = mSamplingRates[minAbove];
6820 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6821 if (updatedSamplingRate != NULL) {
6822 *updatedSamplingRate = candidate;
6823 }
6824 return NO_ERROR;
6825 }
6826 }
6827 // But if we have to up-sample from a lower sampling rate, that's OK.
6828 if (maxBelow >= 0) {
6829 candidate = mSamplingRates[maxBelow];
6830 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6831 if (updatedSamplingRate != NULL) {
6832 *updatedSamplingRate = candidate;
6833 }
6834 return NO_ERROR;
6835 }
6836 }
6837 // leave updatedSamplingRate unmodified
6838 return BAD_VALUE;
6839}
6840
6841status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6842{
Eric Laurent0daea392014-12-04 19:14:54 -08006843 if (mChannelMasks.isEmpty()) {
6844 return NO_ERROR;
6845 }
6846
Glenn Kastencbd48022014-07-24 13:46:44 -07006847 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006848 if (mChannelMasks[i] == channelMask) {
6849 return NO_ERROR;
6850 }
6851 }
6852 return BAD_VALUE;
6853}
6854
Glenn Kastencbd48022014-07-24 13:46:44 -07006855status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6856 const
6857{
Eric Laurent0daea392014-12-04 19:14:54 -08006858 if (mChannelMasks.isEmpty()) {
6859 return NO_ERROR;
6860 }
6861
Glenn Kastencbd48022014-07-24 13:46:44 -07006862 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6863 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6864 // FIXME Does not handle multi-channel automatic conversions yet
6865 audio_channel_mask_t supported = mChannelMasks[i];
6866 if (supported == channelMask) {
6867 return NO_ERROR;
6868 }
6869 if (isRecordThread) {
6870 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6871 // FIXME Abstract this out to a table.
6872 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6873 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6874 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6875 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6876 return NO_ERROR;
6877 }
6878 }
6879 }
6880 return BAD_VALUE;
6881}
6882
Eric Laurenta121f902014-06-03 13:32:54 -07006883status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6884{
Eric Laurent0daea392014-12-04 19:14:54 -08006885 if (mFormats.isEmpty()) {
6886 return NO_ERROR;
6887 }
6888
Eric Laurenta121f902014-06-03 13:32:54 -07006889 for (size_t i = 0; i < mFormats.size(); i ++) {
6890 if (mFormats[i] == format) {
6891 return NO_ERROR;
6892 }
6893 }
6894 return BAD_VALUE;
6895}
6896
Eric Laurent1e693b52014-07-09 15:03:28 -07006897
6898uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6899{
6900 // special case for uninitialized dynamic profile
6901 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6902 return 0;
6903 }
6904
Eric Laurent828bcff2014-09-07 12:26:06 -07006905 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6906 // channel count / sampling rate combination chosen will be supported by the connected
6907 // sink
6908 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6909 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6910 uint32_t samplingRate = UINT_MAX;
6911 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6912 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6913 samplingRate = mSamplingRates[i];
6914 }
6915 }
6916 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6917 }
6918
Eric Laurent1e693b52014-07-09 15:03:28 -07006919 uint32_t samplingRate = 0;
6920 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6921
6922 // For mixed output and inputs, use max mixer sampling rates. Do not
6923 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006924 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006925 maxRate = UINT_MAX;
6926 }
6927 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6928 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6929 samplingRate = mSamplingRates[i];
6930 }
6931 }
6932 return samplingRate;
6933}
6934
6935audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6936{
6937 // special case for uninitialized dynamic profile
6938 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6939 return AUDIO_CHANNEL_NONE;
6940 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006941 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006942
6943 // For direct outputs, pick minimum channel count: this helps ensuring that the
6944 // channel count / sampling rate combination chosen will be supported by the connected
6945 // sink
6946 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6947 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6948 uint32_t channelCount = UINT_MAX;
6949 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6950 uint32_t cnlCount;
6951 if (mUseInChannelMask) {
6952 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6953 } else {
6954 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6955 }
6956 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6957 channelMask = mChannelMasks[i];
6958 channelCount = cnlCount;
6959 }
6960 }
6961 return channelMask;
6962 }
6963
Eric Laurent1e693b52014-07-09 15:03:28 -07006964 uint32_t channelCount = 0;
6965 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6966
6967 // For mixed output and inputs, use max mixer channel count. Do not
6968 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006969 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006970 maxCount = UINT_MAX;
6971 }
6972 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6973 uint32_t cnlCount;
6974 if (mUseInChannelMask) {
6975 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6976 } else {
6977 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6978 }
6979 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6980 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006981 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006982 }
6983 }
6984 return channelMask;
6985}
6986
Andy Hung9a605382014-07-28 16:16:31 -07006987/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006988const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6989 AUDIO_FORMAT_DEFAULT,
6990 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006991 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006992 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006993 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006994 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006995};
6996
6997int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6998 audio_format_t format2)
6999{
7000 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
7001 // compressed format and better than any PCM format. This is by design of pickFormat()
7002 if (!audio_is_linear_pcm(format1)) {
7003 if (!audio_is_linear_pcm(format2)) {
7004 return 0;
7005 }
7006 return 1;
7007 }
7008 if (!audio_is_linear_pcm(format2)) {
7009 return -1;
7010 }
7011
7012 int index1 = -1, index2 = -1;
7013 for (size_t i = 0;
7014 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
7015 i ++) {
7016 if (sPcmFormatCompareTable[i] == format1) {
7017 index1 = i;
7018 }
7019 if (sPcmFormatCompareTable[i] == format2) {
7020 index2 = i;
7021 }
7022 }
7023 // format1 not found => index1 < 0 => format2 > format1
7024 // format2 not found => index2 < 0 => format2 < format1
7025 return index1 - index2;
7026}
7027
7028audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
7029{
7030 // special case for uninitialized dynamic profile
7031 if (mFormats.size() == 1 && mFormats[0] == 0) {
7032 return AUDIO_FORMAT_DEFAULT;
7033 }
7034
7035 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07007036 audio_format_t bestFormat =
7037 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
7038 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07007039 // For mixed output and inputs, use best mixer output format. Do not
7040 // limit format otherwise
7041 if ((mType != AUDIO_PORT_TYPE_MIX) ||
7042 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07007043 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007044 bestFormat = AUDIO_FORMAT_INVALID;
7045 }
7046
7047 for (size_t i = 0; i < mFormats.size(); i ++) {
7048 if ((compareFormats(mFormats[i], format) > 0) &&
7049 (compareFormats(mFormats[i], bestFormat) <= 0)) {
7050 format = mFormats[i];
7051 }
7052 }
7053 return format;
7054}
7055
Eric Laurenta121f902014-06-03 13:32:54 -07007056status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
7057 int index) const
7058{
7059 if (index < 0 || (size_t)index >= mGains.size()) {
7060 return BAD_VALUE;
7061 }
7062 return mGains[index]->checkConfig(gainConfig);
7063}
7064
Eric Laurent1afeecb2014-05-14 08:52:28 -07007065void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
7066{
7067 const size_t SIZE = 256;
7068 char buffer[SIZE];
7069 String8 result;
7070
7071 if (mName.size() != 0) {
7072 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
7073 result.append(buffer);
7074 }
7075
7076 if (mSamplingRates.size() != 0) {
7077 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
7078 result.append(buffer);
7079 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007080 if (i == 0 && mSamplingRates[i] == 0) {
7081 snprintf(buffer, SIZE, "Dynamic");
7082 } else {
7083 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
7084 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007085 result.append(buffer);
7086 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
7087 }
7088 result.append("\n");
7089 }
7090
7091 if (mChannelMasks.size() != 0) {
7092 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
7093 result.append(buffer);
7094 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007095 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
7096
7097 if (i == 0 && mChannelMasks[i] == 0) {
7098 snprintf(buffer, SIZE, "Dynamic");
7099 } else {
7100 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
7101 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007102 result.append(buffer);
7103 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
7104 }
7105 result.append("\n");
7106 }
7107
7108 if (mFormats.size() != 0) {
7109 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
7110 result.append(buffer);
7111 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007112 const char *formatStr = enumToString(sFormatNameToEnumTable,
7113 ARRAY_SIZE(sFormatNameToEnumTable),
7114 mFormats[i]);
7115 if (i == 0 && strcmp(formatStr, "") == 0) {
7116 snprintf(buffer, SIZE, "Dynamic");
7117 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07007118 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07007119 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007120 result.append(buffer);
7121 result.append(i == (mFormats.size() - 1) ? "" : ", ");
7122 }
7123 result.append("\n");
7124 }
7125 write(fd, result.string(), result.size());
7126 if (mGains.size() != 0) {
7127 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
7128 write(fd, buffer, strlen(buffer) + 1);
7129 result.append(buffer);
7130 for (size_t i = 0; i < mGains.size(); i++) {
7131 mGains[i]->dump(fd, spaces + 2, i);
7132 }
7133 }
7134}
7135
7136// --- AudioGain class implementation
7137
Eric Laurenta121f902014-06-03 13:32:54 -07007138AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07007139{
Eric Laurenta121f902014-06-03 13:32:54 -07007140 mIndex = index;
7141 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007142 memset(&mGain, 0, sizeof(struct audio_gain));
7143}
7144
Eric Laurenta121f902014-06-03 13:32:54 -07007145void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
7146{
7147 config->index = mIndex;
7148 config->mode = mGain.mode;
7149 config->channel_mask = mGain.channel_mask;
7150 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7151 config->values[0] = mGain.default_value;
7152 } else {
7153 uint32_t numValues;
7154 if (mUseInChannelMask) {
7155 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
7156 } else {
7157 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
7158 }
7159 for (size_t i = 0; i < numValues; i++) {
7160 config->values[i] = mGain.default_value;
7161 }
7162 }
7163 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7164 config->ramp_duration_ms = mGain.min_ramp_ms;
7165 }
7166}
7167
7168status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
7169{
7170 if ((config->mode & ~mGain.mode) != 0) {
7171 return BAD_VALUE;
7172 }
7173 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7174 if ((config->values[0] < mGain.min_value) ||
7175 (config->values[0] > mGain.max_value)) {
7176 return BAD_VALUE;
7177 }
7178 } else {
7179 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
7180 return BAD_VALUE;
7181 }
7182 uint32_t numValues;
7183 if (mUseInChannelMask) {
7184 numValues = audio_channel_count_from_in_mask(config->channel_mask);
7185 } else {
7186 numValues = audio_channel_count_from_out_mask(config->channel_mask);
7187 }
7188 for (size_t i = 0; i < numValues; i++) {
7189 if ((config->values[i] < mGain.min_value) ||
7190 (config->values[i] > mGain.max_value)) {
7191 return BAD_VALUE;
7192 }
7193 }
7194 }
7195 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7196 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
7197 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
7198 return BAD_VALUE;
7199 }
7200 }
7201 return NO_ERROR;
7202}
7203
Eric Laurent1afeecb2014-05-14 08:52:28 -07007204void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
7205{
7206 const size_t SIZE = 256;
7207 char buffer[SIZE];
7208 String8 result;
7209
7210 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
7211 result.append(buffer);
7212 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
7213 result.append(buffer);
7214 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
7215 result.append(buffer);
7216 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
7217 result.append(buffer);
7218 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
7219 result.append(buffer);
7220 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
7221 result.append(buffer);
7222 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
7223 result.append(buffer);
7224 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
7225 result.append(buffer);
7226 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
7227 result.append(buffer);
7228
7229 write(fd, result.string(), result.size());
7230}
7231
Eric Laurent1f2f2232014-06-02 12:01:23 -07007232// --- AudioPortConfig class implementation
7233
7234AudioPolicyManager::AudioPortConfig::AudioPortConfig()
7235{
7236 mSamplingRate = 0;
7237 mChannelMask = AUDIO_CHANNEL_NONE;
7238 mFormat = AUDIO_FORMAT_INVALID;
7239 mGain.index = -1;
7240}
7241
Eric Laurenta121f902014-06-03 13:32:54 -07007242status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
7243 const struct audio_port_config *config,
7244 struct audio_port_config *backupConfig)
7245{
7246 struct audio_port_config localBackupConfig;
7247 status_t status = NO_ERROR;
7248
7249 localBackupConfig.config_mask = config->config_mask;
7250 toAudioPortConfig(&localBackupConfig);
7251
Marco Nelissen961ec212014-08-25 15:58:39 -07007252 sp<AudioPort> audioport = getAudioPort();
7253 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07007254 status = NO_INIT;
7255 goto exit;
7256 }
7257 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007258 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07007259 if (status != NO_ERROR) {
7260 goto exit;
7261 }
7262 mSamplingRate = config->sample_rate;
7263 }
7264 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007265 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07007266 if (status != NO_ERROR) {
7267 goto exit;
7268 }
7269 mChannelMask = config->channel_mask;
7270 }
7271 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007272 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07007273 if (status != NO_ERROR) {
7274 goto exit;
7275 }
7276 mFormat = config->format;
7277 }
7278 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007279 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07007280 if (status != NO_ERROR) {
7281 goto exit;
7282 }
7283 mGain = config->gain;
7284 }
7285
7286exit:
7287 if (status != NO_ERROR) {
7288 applyAudioPortConfig(&localBackupConfig);
7289 }
7290 if (backupConfig != NULL) {
7291 *backupConfig = localBackupConfig;
7292 }
7293 return status;
7294}
7295
Eric Laurent1f2f2232014-06-02 12:01:23 -07007296void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
7297 struct audio_port_config *dstConfig,
7298 const struct audio_port_config *srcConfig) const
7299{
7300 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
7301 dstConfig->sample_rate = mSamplingRate;
7302 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
7303 dstConfig->sample_rate = srcConfig->sample_rate;
7304 }
7305 } else {
7306 dstConfig->sample_rate = 0;
7307 }
7308 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
7309 dstConfig->channel_mask = mChannelMask;
7310 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
7311 dstConfig->channel_mask = srcConfig->channel_mask;
7312 }
7313 } else {
7314 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
7315 }
7316 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
7317 dstConfig->format = mFormat;
7318 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
7319 dstConfig->format = srcConfig->format;
7320 }
7321 } else {
7322 dstConfig->format = AUDIO_FORMAT_INVALID;
7323 }
7324 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
7325 dstConfig->gain = mGain;
7326 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
7327 dstConfig->gain = srcConfig->gain;
7328 }
7329 } else {
7330 dstConfig->gain.index = -1;
7331 }
7332 if (dstConfig->gain.index != -1) {
7333 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
7334 } else {
7335 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
7336 }
7337}
7338
Eric Laurent1c333e22014-05-20 10:48:17 -07007339// --- IOProfile class implementation
7340
Eric Laurent1afeecb2014-05-14 08:52:28 -07007341AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07007342 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07007343 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07007344{
7345}
7346
Eric Laurente0720872014-03-11 09:30:41 -07007347AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07007348{
7349}
7350
7351// checks if the IO profile is compatible with specified parameters.
7352// Sampling rate, format and channel mask must be specified in order to
7353// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07007354bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08007355 String8 address,
7356 uint32_t samplingRate,
7357 uint32_t *updatedSamplingRate,
7358 audio_format_t format,
7359 audio_channel_mask_t channelMask,
7360 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07007361{
Glenn Kastencbd48022014-07-24 13:46:44 -07007362 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
7363 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
7364 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07007365
Eric Laurent275e8e92014-11-30 15:14:47 -08007366 if (device != AUDIO_DEVICE_NONE && mSupportedDevices.getDevice(device, address) == 0) {
Glenn Kastencbd48022014-07-24 13:46:44 -07007367 return false;
7368 }
7369
7370 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07007371 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007372 }
7373 uint32_t myUpdatedSamplingRate = samplingRate;
7374 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007375 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007376 }
7377 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
7378 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007379 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007380 }
7381
7382 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
7383 return false;
7384 }
7385
7386 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
7387 checkExactChannelMask(channelMask) != NO_ERROR)) {
7388 return false;
7389 }
7390 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
7391 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
7392 return false;
7393 }
7394
7395 if (isPlaybackThread && (mFlags & flags) != flags) {
7396 return false;
7397 }
7398 // The only input flag that is allowed to be different is the fast flag.
7399 // An existing fast stream is compatible with a normal track request.
7400 // An existing normal stream is compatible with a fast track request,
7401 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07007402 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07007403 ~AUDIO_INPUT_FLAG_FAST)) {
7404 return false;
7405 }
7406
7407 if (updatedSamplingRate != NULL) {
7408 *updatedSamplingRate = myUpdatedSamplingRate;
7409 }
7410 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07007411}
7412
Eric Laurente0720872014-03-11 09:30:41 -07007413void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07007414{
7415 const size_t SIZE = 256;
7416 char buffer[SIZE];
7417 String8 result;
7418
Eric Laurent1afeecb2014-05-14 08:52:28 -07007419 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007420
Eric Laurente552edb2014-03-10 17:42:56 -07007421 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
7422 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007423 snprintf(buffer, SIZE, " - devices:\n");
7424 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07007425 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07007426 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
7427 mSupportedDevices[i]->dump(fd, 6, i);
7428 }
Eric Laurente552edb2014-03-10 17:42:56 -07007429}
7430
Eric Laurentd4692962014-05-05 18:13:44 -07007431void AudioPolicyManager::IOProfile::log()
7432{
7433 const size_t SIZE = 256;
7434 char buffer[SIZE];
7435 String8 result;
7436
7437 ALOGV(" - sampling rates: ");
7438 for (size_t i = 0; i < mSamplingRates.size(); i++) {
7439 ALOGV(" %d", mSamplingRates[i]);
7440 }
7441
7442 ALOGV(" - channel masks: ");
7443 for (size_t i = 0; i < mChannelMasks.size(); i++) {
7444 ALOGV(" 0x%04x", mChannelMasks[i]);
7445 }
7446
7447 ALOGV(" - formats: ");
7448 for (size_t i = 0; i < mFormats.size(); i++) {
7449 ALOGV(" 0x%08x", mFormats[i]);
7450 }
7451
7452 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
7453 ALOGV(" - flags: 0x%04x\n", mFlags);
7454}
7455
7456
Eric Laurent3a4311c2014-03-17 12:00:47 -07007457// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07007458
Eric Laurent1f2f2232014-06-02 12:01:23 -07007459
7460AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
7461 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7462 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7463 AUDIO_PORT_ROLE_SOURCE,
7464 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07007465 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07007466{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007467}
7468
Eric Laurent3a4311c2014-03-17 12:00:47 -07007469bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07007470{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007471 // Devices are considered equal if they:
7472 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7473 // - have the same address or one device does not specify the address
7474 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007475 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007476 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007477 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007478 mChannelMask == other->mChannelMask);
7479}
7480
Eric Laurent1db89b92015-01-27 18:21:09 -08007481void AudioPolicyManager::DeviceDescriptor::loadGains(cnode *root)
7482{
7483 AudioPort::loadGains(root);
7484 if (mGains.size() > 0) {
7485 mGains[0]->getDefaultConfig(&mGain);
7486 }
7487}
7488
7489
Eric Laurent3a4311c2014-03-17 12:00:47 -07007490void AudioPolicyManager::DeviceVector::refreshTypes()
7491{
Eric Laurent1c333e22014-05-20 10:48:17 -07007492 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007493 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007494 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007495 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007496 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007497}
7498
7499ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7500{
7501 for(size_t i = 0; i < size(); i++) {
7502 if (item->equals(itemAt(i))) {
7503 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007504 }
7505 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007506 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007507}
7508
Eric Laurent3a4311c2014-03-17 12:00:47 -07007509ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007510{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007511 ssize_t ret = indexOf(item);
7512
7513 if (ret < 0) {
7514 ret = SortedVector::add(item);
7515 if (ret >= 0) {
7516 refreshTypes();
7517 }
7518 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007519 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007520 ret = -1;
7521 }
7522 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007523}
7524
Eric Laurent3a4311c2014-03-17 12:00:47 -07007525ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7526{
7527 size_t i;
7528 ssize_t ret = indexOf(item);
7529
7530 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007531 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007532 } else {
7533 ret = SortedVector::removeAt(ret);
7534 if (ret >= 0) {
7535 refreshTypes();
7536 }
7537 }
7538 return ret;
7539}
7540
7541void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7542{
7543 DeviceVector deviceList;
7544
7545 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7546 types &= ~role_bit;
7547
7548 while (types) {
7549 uint32_t i = 31 - __builtin_clz(types);
7550 uint32_t type = 1 << i;
7551 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007552 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007553 }
7554}
7555
Eric Laurent1afeecb2014-05-14 08:52:28 -07007556void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7557 const DeviceVector& declaredDevices)
7558{
7559 char *devName = strtok(name, "|");
7560 while (devName != NULL) {
7561 if (strlen(devName) != 0) {
7562 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7563 ARRAY_SIZE(sDeviceNameToEnumTable),
7564 devName);
7565 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007566 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
Eric Laurent275e8e92014-11-30 15:14:47 -08007567 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX ||
7568 type == AUDIO_DEVICE_OUT_REMOTE_SUBMIX ) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007569 dev->mAddress = String8("0");
7570 }
7571 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007572 } else {
7573 sp<DeviceDescriptor> deviceDesc =
7574 declaredDevices.getDeviceFromName(String8(devName));
7575 if (deviceDesc != 0) {
7576 add(deviceDesc);
7577 }
7578 }
7579 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007580 devName = strtok(NULL, "|");
Eric Laurent1afeecb2014-05-14 08:52:28 -07007581 }
7582}
7583
Eric Laurent1c333e22014-05-20 10:48:17 -07007584sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7585 audio_devices_t type, String8 address) const
7586{
7587 sp<DeviceDescriptor> device;
7588 for (size_t i = 0; i < size(); i++) {
7589 if (itemAt(i)->mDeviceType == type) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007590 if (address == "" || itemAt(i)->mAddress == address) {
7591 device = itemAt(i);
7592 if (itemAt(i)->mAddress == address) {
7593 break;
7594 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007595 }
7596 }
7597 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007598 ALOGV("DeviceVector::getDevice() for type %08x address %s found %p",
Eric Laurent1c333e22014-05-20 10:48:17 -07007599 type, address.string(), device.get());
7600 return device;
7601}
7602
Eric Laurent6a94d692014-05-20 11:18:06 -07007603sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7604 audio_port_handle_t id) const
7605{
7606 sp<DeviceDescriptor> device;
7607 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007608 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007609 if (itemAt(i)->mId == id) {
7610 device = itemAt(i);
7611 break;
7612 }
7613 }
7614 return device;
7615}
7616
Eric Laurent1c333e22014-05-20 10:48:17 -07007617AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7618 audio_devices_t type) const
7619{
7620 DeviceVector devices;
7621 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7622 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7623 devices.add(itemAt(i));
7624 type &= ~itemAt(i)->mDeviceType;
7625 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7626 itemAt(i)->mDeviceType, itemAt(i).get());
7627 }
7628 }
7629 return devices;
7630}
7631
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007632AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7633 audio_devices_t type, String8 address) const
7634{
7635 DeviceVector devices;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007636 for (size_t i = 0; i < size(); i++) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007637 if (itemAt(i)->mDeviceType == type) {
7638 if (itemAt(i)->mAddress == address) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007639 devices.add(itemAt(i));
7640 }
7641 }
7642 }
7643 return devices;
7644}
7645
Eric Laurent1afeecb2014-05-14 08:52:28 -07007646sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7647 const String8& name) const
7648{
7649 sp<DeviceDescriptor> device;
7650 for (size_t i = 0; i < size(); i++) {
7651 if (itemAt(i)->mName == name) {
7652 device = itemAt(i);
7653 break;
7654 }
7655 }
7656 return device;
7657}
7658
Eric Laurent6a94d692014-05-20 11:18:06 -07007659void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7660 struct audio_port_config *dstConfig,
7661 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007662{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007663 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7664 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007665 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007666 }
7667
7668 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7669
Eric Laurent6a94d692014-05-20 11:18:06 -07007670 dstConfig->id = mId;
7671 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007672 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007673 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007674 dstConfig->ext.device.type = mDeviceType;
7675 dstConfig->ext.device.hw_module = mModule->mHandle;
7676 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007677}
7678
7679void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7680{
Eric Laurent83b88082014-06-20 18:31:16 -07007681 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007682 AudioPort::toAudioPort(port);
7683 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007684 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007685 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007686 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007687 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7688}
7689
Eric Laurent1afeecb2014-05-14 08:52:28 -07007690status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007691{
7692 const size_t SIZE = 256;
7693 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007694 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007695
Eric Laurent1afeecb2014-05-14 08:52:28 -07007696 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7697 result.append(buffer);
7698 if (mId != 0) {
7699 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7700 result.append(buffer);
7701 }
7702 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7703 enumToString(sDeviceNameToEnumTable,
7704 ARRAY_SIZE(sDeviceNameToEnumTable),
7705 mDeviceType));
7706 result.append(buffer);
7707 if (mAddress.size() != 0) {
7708 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7709 result.append(buffer);
7710 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007711 write(fd, result.string(), result.size());
7712 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007713
7714 return NO_ERROR;
7715}
7716
Eric Laurent4d416952014-08-10 14:07:09 -07007717status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7718{
7719 const size_t SIZE = 256;
7720 char buffer[SIZE];
7721 String8 result;
7722
7723
7724 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7725 result.append(buffer);
7726 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7727 result.append(buffer);
7728 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7729 result.append(buffer);
7730 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7731 result.append(buffer);
7732 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7733 result.append(buffer);
7734 for (size_t i = 0; i < mPatch.num_sources; i++) {
7735 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7736 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7737 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7738 ARRAY_SIZE(sDeviceNameToEnumTable),
7739 mPatch.sources[i].ext.device.type));
7740 } else {
7741 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7742 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7743 }
7744 result.append(buffer);
7745 }
7746 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7747 result.append(buffer);
7748 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7749 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7750 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7751 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7752 ARRAY_SIZE(sDeviceNameToEnumTable),
7753 mPatch.sinks[i].ext.device.type));
7754 } else {
7755 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7756 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7757 }
7758 result.append(buffer);
7759 }
7760
7761 write(fd, result.string(), result.size());
7762 return NO_ERROR;
7763}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007764
7765// --- audio_policy.conf file parsing
7766
Eric Laurent5dbe4712014-09-19 19:04:57 -07007767uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007768{
7769 uint32_t flag = 0;
7770
7771 // it is OK to cast name to non const here as we are not going to use it after
7772 // strtok() modifies it
7773 char *flagName = strtok(name, "|");
7774 while (flagName != NULL) {
7775 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007776 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7777 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007778 flagName);
7779 }
7780 flagName = strtok(NULL, "|");
7781 }
7782 //force direct flag if offload flag is set: offloading implies a direct output stream
7783 // and all common behaviors are driven by checking only the direct flag
7784 // this should normally be set appropriately in the policy configuration file
7785 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7786 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7787 }
7788
Eric Laurent5dbe4712014-09-19 19:04:57 -07007789 return flag;
7790}
7791
7792uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7793{
7794 uint32_t flag = 0;
7795
7796 // it is OK to cast name to non const here as we are not going to use it after
7797 // strtok() modifies it
7798 char *flagName = strtok(name, "|");
7799 while (flagName != NULL) {
7800 if (strlen(flagName) != 0) {
7801 flag |= stringToEnum(sInputFlagNameToEnumTable,
7802 ARRAY_SIZE(sInputFlagNameToEnumTable),
7803 flagName);
7804 }
7805 flagName = strtok(NULL, "|");
7806 }
7807 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007808}
7809
Eric Laurente0720872014-03-11 09:30:41 -07007810audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007811{
7812 uint32_t device = 0;
7813
7814 char *devName = strtok(name, "|");
7815 while (devName != NULL) {
7816 if (strlen(devName) != 0) {
7817 device |= stringToEnum(sDeviceNameToEnumTable,
7818 ARRAY_SIZE(sDeviceNameToEnumTable),
7819 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007820 }
Eric Laurente552edb2014-03-10 17:42:56 -07007821 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007822 }
Eric Laurente552edb2014-03-10 17:42:56 -07007823 return device;
7824}
7825
Eric Laurente0720872014-03-11 09:30:41 -07007826void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007827{
Eric Laurente552edb2014-03-10 17:42:56 -07007828 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007829 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007830 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007831
Eric Laurent1afeecb2014-05-14 08:52:28 -07007832 node = config_find(root, DEVICES_TAG);
7833 if (node != NULL) {
7834 node = node->first_child;
7835 while (node) {
7836 ALOGV("loadHwModule() loading device %s", node->name);
7837 status_t tmpStatus = module->loadDevice(node);
7838 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7839 status = tmpStatus;
7840 }
7841 node = node->next;
7842 }
7843 }
7844 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007845 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007846 node = node->first_child;
7847 while (node) {
7848 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007849 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007850 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7851 status = tmpStatus;
7852 }
7853 node = node->next;
7854 }
7855 }
7856 node = config_find(root, INPUTS_TAG);
7857 if (node != NULL) {
7858 node = node->first_child;
7859 while (node) {
7860 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007861 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007862 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7863 status = tmpStatus;
7864 }
7865 node = node->next;
7866 }
7867 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007868 loadGlobalConfig(root, module);
7869
Eric Laurente552edb2014-03-10 17:42:56 -07007870 if (status == NO_ERROR) {
7871 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007872 }
7873}
7874
Eric Laurente0720872014-03-11 09:30:41 -07007875void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007876{
7877 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7878 if (node == NULL) {
7879 return;
7880 }
7881
7882 node = node->first_child;
7883 while (node) {
7884 ALOGV("loadHwModules() loading module %s", node->name);
7885 loadHwModule(node);
7886 node = node->next;
7887 }
7888}
7889
Eric Laurent1f2f2232014-06-02 12:01:23 -07007890void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007891{
7892 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007893
Eric Laurente552edb2014-03-10 17:42:56 -07007894 if (node == NULL) {
7895 return;
7896 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007897 DeviceVector declaredDevices;
7898 if (module != NULL) {
7899 declaredDevices = module->mDeclaredDevices;
7900 }
7901
Eric Laurente552edb2014-03-10 17:42:56 -07007902 node = node->first_child;
7903 while (node) {
7904 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007905 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7906 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007907 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7908 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007909 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007910 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007911 ARRAY_SIZE(sDeviceNameToEnumTable),
7912 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007913 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007914 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007915 } else {
7916 ALOGW("loadGlobalConfig() default device not specified");
7917 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007918 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007919 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007920 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7921 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007922 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007923 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7924 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7925 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007926 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7927 uint32_t major, minor;
7928 sscanf((char *)node->value, "%u.%u", &major, &minor);
7929 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7930 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7931 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007932 }
7933 node = node->next;
7934 }
7935}
7936
Eric Laurente0720872014-03-11 09:30:41 -07007937status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007938{
7939 cnode *root;
7940 char *data;
7941
7942 data = (char *)load_file(path, NULL);
7943 if (data == NULL) {
7944 return -ENODEV;
7945 }
7946 root = config_node("", "");
7947 config_load(root, data);
7948
Eric Laurente552edb2014-03-10 17:42:56 -07007949 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007950 // legacy audio_policy.conf files have one global_configuration section
7951 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007952 config_free(root);
7953 free(root);
7954 free(data);
7955
7956 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7957
7958 return NO_ERROR;
7959}
7960
Eric Laurente0720872014-03-11 09:30:41 -07007961void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007962{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007963 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007964 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007965 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7966 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007967 mAvailableOutputDevices.add(mDefaultOutputDevice);
7968 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007969
7970 module = new HwModule("primary");
7971
Eric Laurent1afeecb2014-05-14 08:52:28 -07007972 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007973 profile->mSamplingRates.add(44100);
7974 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7975 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007976 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007977 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7978 module->mOutputProfiles.add(profile);
7979
Eric Laurent1afeecb2014-05-14 08:52:28 -07007980 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007981 profile->mSamplingRates.add(8000);
7982 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7983 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007984 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007985 module->mInputProfiles.add(profile);
7986
7987 mHwModules.add(module);
7988}
7989
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007990audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7991{
7992 // flags to stream type mapping
7993 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7994 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7995 }
7996 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7997 return AUDIO_STREAM_BLUETOOTH_SCO;
7998 }
7999
8000 // usage to stream type mapping
8001 switch (attr->usage) {
8002 case AUDIO_USAGE_MEDIA:
8003 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07008004 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8005 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08008006 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08008007 if (isStreamActive(AUDIO_STREAM_ALARM)) {
8008 return AUDIO_STREAM_ALARM;
8009 }
8010 if (isStreamActive(AUDIO_STREAM_RING)) {
8011 return AUDIO_STREAM_RING;
8012 }
8013 if (isInCall()) {
8014 return AUDIO_STREAM_VOICE_CALL;
8015 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08008016 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07008017 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8018 return AUDIO_STREAM_SYSTEM;
8019 case AUDIO_USAGE_VOICE_COMMUNICATION:
8020 return AUDIO_STREAM_VOICE_CALL;
8021
8022 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8023 return AUDIO_STREAM_DTMF;
8024
8025 case AUDIO_USAGE_ALARM:
8026 return AUDIO_STREAM_ALARM;
8027 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8028 return AUDIO_STREAM_RING;
8029
8030 case AUDIO_USAGE_NOTIFICATION:
8031 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8032 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8033 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8034 case AUDIO_USAGE_NOTIFICATION_EVENT:
8035 return AUDIO_STREAM_NOTIFICATION;
8036
8037 case AUDIO_USAGE_UNKNOWN:
8038 default:
8039 return AUDIO_STREAM_MUSIC;
8040 }
8041}
Eric Laurente83b55d2014-11-14 10:06:21 -08008042
8043bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
8044 // has flags that map to a strategy?
8045 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8046 return true;
8047 }
8048
8049 // has known usage?
8050 switch (paa->usage) {
8051 case AUDIO_USAGE_UNKNOWN:
8052 case AUDIO_USAGE_MEDIA:
8053 case AUDIO_USAGE_VOICE_COMMUNICATION:
8054 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8055 case AUDIO_USAGE_ALARM:
8056 case AUDIO_USAGE_NOTIFICATION:
8057 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8058 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8059 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8060 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8061 case AUDIO_USAGE_NOTIFICATION_EVENT:
8062 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8063 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8064 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8065 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008066 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08008067 break;
8068 default:
8069 return false;
8070 }
8071 return true;
8072}
8073
Eric Laurente552edb2014-03-10 17:42:56 -07008074}; // namespace android