blob: 5a0c9582e79ab3b7330d6bcf27d1d2928332201e [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,
Paul McLeane743a472015-01-28 11:07:31 -0800215 audio_policy_dev_state_t state,
216 const char *device_address,
217 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -0700218{
Paul McLeane743a472015-01-28 11:07:31 -0800219 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800220}
221
222status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800223 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800224 const char *device_address,
225 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800226{
Paul McLeane743a472015-01-28 11:07:31 -0800227 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
228- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700229
230 // connect/disconnect only 1 device at a time
231 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
232
Eric Laurenta1d525f2015-01-29 13:36:45 -0800233 sp<DeviceDescriptor> devDesc = getDeviceDescriptor(device, device_address);
234
Paul McLeane743a472015-01-28 11:07:31 -0800235 String8 name = String8(device_name != NULL ? device_name : "");
236
Eric Laurente552edb2014-03-10 17:42:56 -0700237 // handle output devices
238 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700239 SortedVector <audio_io_handle_t> outputs;
240
Eric Laurent3a4311c2014-03-17 12:00:47 -0700241 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
242
Eric Laurente552edb2014-03-10 17:42:56 -0700243 // save a copy of the opened output descriptors before any output is opened or closed
244 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
245 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700246 switch (state)
247 {
248 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800249 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700250 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700251 ALOGW("setDeviceConnectionState() device already connected: %x", device);
252 return INVALID_OPERATION;
253 }
254 ALOGV("setDeviceConnectionState() connecting device %x", device);
255
Eric Laurente552edb2014-03-10 17:42:56 -0700256 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700257 index = mAvailableOutputDevices.add(devDesc);
258 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700259 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700260 if (module == 0) {
261 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
262 device);
263 mAvailableOutputDevices.remove(devDesc);
264 return INVALID_OPERATION;
265 }
Paul McLeane743a472015-01-28 11:07:31 -0800266 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700267 } else {
268 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700269 }
270
Eric Laurenta1d525f2015-01-29 13:36:45 -0800271 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700272 mAvailableOutputDevices.remove(devDesc);
273 return INVALID_OPERATION;
274 }
275 // outputs should never be empty here
276 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
277 "checkOutputsForDevice() returned no outputs but status OK");
278 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
279 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800280
281
282 // Set connect to HALs
283 AudioParameter param = AudioParameter(devDesc->mAddress);
284 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
285 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
286
287 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700288 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700289 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700290 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700291 ALOGW("setDeviceConnectionState() device not connected: %x", device);
292 return INVALID_OPERATION;
293 }
294
Paul McLean5c477aa2014-08-20 16:47:57 -0700295 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
296
Paul McLeane743a472015-01-28 11:07:31 -0800297 // Send Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800298 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700299 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
300 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
301
Eric Laurente552edb2014-03-10 17:42:56 -0700302 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700303 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700304
Eric Laurenta1d525f2015-01-29 13:36:45 -0800305 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
Eric Laurente552edb2014-03-10 17:42:56 -0700306 } break;
307
308 default:
309 ALOGE("setDeviceConnectionState() invalid state: %x", state);
310 return BAD_VALUE;
311 }
312
Eric Laurent3a4311c2014-03-17 12:00:47 -0700313 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
314 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700315 checkA2dpSuspend();
316 checkOutputForAllStrategies();
317 // outputs must be closed after checkOutputForAllStrategies() is executed
318 if (!outputs.isEmpty()) {
319 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700320 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700321 // close unused outputs after device disconnection or direct outputs that have been
322 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700323 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700324 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
325 (desc->mDirectOpenCount == 0))) {
326 closeOutput(outputs[i]);
327 }
328 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700329 // check again after closing A2DP output to reset mA2dpSuspended if needed
330 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700331 }
332
333 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700334 if (mPhoneState == AUDIO_MODE_IN_CALL) {
335 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
336 updateCallRouting(newDevice);
337 }
Eric Laurente552edb2014-03-10 17:42:56 -0700338 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 audio_io_handle_t output = mOutputs.keyAt(i);
340 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
341 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
342 true /*fromCache*/);
343 // do not force device change on duplicated output because if device is 0, it will
344 // also force a device 0 for the two outputs it is duplicated to which may override
345 // a valid device selection on those outputs.
346 bool force = !mOutputs.valueAt(i)->isDuplicated()
347 && (!deviceDistinguishesOnAddress(device)
348 // always force when disconnecting (a non-duplicated device)
349 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
350 setOutputDevice(output, newDevice, force, 0);
351 }
Eric Laurente552edb2014-03-10 17:42:56 -0700352 }
353
Eric Laurent72aa32f2014-05-30 18:51:48 -0700354 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700355 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700356 } // end if is output device
357
Eric Laurente552edb2014-03-10 17:42:56 -0700358 // handle input devices
359 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700360 SortedVector <audio_io_handle_t> inputs;
361
Eric Laurent3a4311c2014-03-17 12:00:47 -0700362 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700363 switch (state)
364 {
365 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700366 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700367 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700368 ALOGW("setDeviceConnectionState() device already connected: %d", device);
369 return INVALID_OPERATION;
370 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700371 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700372 if (module == NULL) {
373 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
374 device);
375 return INVALID_OPERATION;
376 }
Eric Laurenta1d525f2015-01-29 13:36:45 -0800377 if (checkInputsForDevice(device, state, inputs, devDesc->mAddress) != NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -0700378 return INVALID_OPERATION;
379 }
380
Eric Laurent3a4311c2014-03-17 12:00:47 -0700381 index = mAvailableInputDevices.add(devDesc);
382 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800383 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700384 } else {
385 return NO_MEMORY;
386 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800387
388 // Set connect to HALs
389 AudioParameter param = AudioParameter(devDesc->mAddress);
390 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
391 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
392
Eric Laurentd4692962014-05-05 18:13:44 -0700393 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700394
395 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700396 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700397 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700398 ALOGW("setDeviceConnectionState() device not connected: %d", device);
399 return INVALID_OPERATION;
400 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700401
402 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
403
404 // Set Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800405 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700406 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
407 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
408
Eric Laurenta1d525f2015-01-29 13:36:45 -0800409 checkInputsForDevice(device, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700410 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700411
Eric Laurentd4692962014-05-05 18:13:44 -0700412 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700413
414 default:
415 ALOGE("setDeviceConnectionState() invalid state: %x", state);
416 return BAD_VALUE;
417 }
418
Eric Laurentd4692962014-05-05 18:13:44 -0700419 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700420
Eric Laurentc2730ba2014-07-20 15:47:07 -0700421 if (mPhoneState == AUDIO_MODE_IN_CALL) {
422 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
423 updateCallRouting(newDevice);
424 }
425
Eric Laurentb52c1522014-05-20 11:27:36 -0700426 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700427 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700428 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700429
430 ALOGW("setDeviceConnectionState() invalid device: %x", device);
431 return BAD_VALUE;
432}
433
Eric Laurente0720872014-03-11 09:30:41 -0700434audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700435 const char *device_address)
436{
Eric Laurenta1d525f2015-01-29 13:36:45 -0800437 sp<DeviceDescriptor> devDesc = getDeviceDescriptor(device, device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700438 DeviceVector *deviceVector;
439
Eric Laurente552edb2014-03-10 17:42:56 -0700440 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700441 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700442 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700443 deviceVector = &mAvailableInputDevices;
444 } else {
445 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
446 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700447 }
448
Eric Laurenta1d525f2015-01-29 13:36:45 -0800449 ssize_t index = deviceVector->indexOf(devDesc);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700450 if (index >= 0) {
451 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
452 } else {
453 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
454 }
Eric Laurente552edb2014-03-10 17:42:56 -0700455}
456
Eric Laurenta1d525f2015-01-29 13:36:45 -0800457sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::getDeviceDescriptor(
458 const audio_devices_t device,
459 const char *device_address)
460{
461 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
462 // handle legacy remote submix case where the address was not always specified
463 if (deviceDistinguishesOnAddress(device) && (address.length() == 0)) {
464 address = String8("0");
465 }
466
467 for (size_t i = 0; i < mHwModules.size(); i++) {
468 if (mHwModules[i]->mHandle == 0) {
469 continue;
470 }
471 DeviceVector deviceList =
472 mHwModules[i]->mDeclaredDevices.getDevicesFromTypeAddr(device, address);
473 if (!deviceList.isEmpty()) {
474 return deviceList.itemAt(0);
475 }
476 deviceList = mHwModules[i]->mDeclaredDevices.getDevicesFromType(device);
477 if (!deviceList.isEmpty()) {
478 return deviceList.itemAt(0);
479 }
480 }
481
482 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
483 devDesc->mAddress = address;
484 return devDesc;
485}
486
Eric Laurentc2730ba2014-07-20 15:47:07 -0700487void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
488{
489 bool createTxPatch = false;
490 struct audio_patch patch;
491 patch.num_sources = 1;
492 patch.num_sinks = 1;
493 status_t status;
494 audio_patch_handle_t afPatchHandle;
495 DeviceVector deviceList;
496
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800497 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700498 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
499
500 // release existing RX patch if any
501 if (mCallRxPatch != 0) {
502 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
503 mCallRxPatch.clear();
504 }
505 // release TX patch if any
506 if (mCallTxPatch != 0) {
507 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
508 mCallTxPatch.clear();
509 }
510
511 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
512 // via setOutputDevice() on primary output.
513 // Otherwise, create two audio patches for TX and RX path.
514 if (availablePrimaryOutputDevices() & rxDevice) {
515 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
516 // If the TX device is also on the primary HW module, setOutputDevice() will take care
517 // of it due to legacy implementation. If not, create a patch.
518 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
519 == AUDIO_DEVICE_NONE) {
520 createTxPatch = true;
521 }
522 } else {
523 // create RX path audio patch
524 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
525 ALOG_ASSERT(!deviceList.isEmpty(),
526 "updateCallRouting() selected device not in output device list");
527 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
528 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
529 ALOG_ASSERT(!deviceList.isEmpty(),
530 "updateCallRouting() no telephony RX device");
531 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
532
533 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
534 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
535
536 // request to reuse existing output stream if one is already opened to reach the RX device
537 SortedVector<audio_io_handle_t> outputs =
538 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700539 audio_io_handle_t output = selectOutput(outputs,
540 AUDIO_OUTPUT_FLAG_NONE,
541 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700542 if (output != AUDIO_IO_HANDLE_NONE) {
543 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
544 ALOG_ASSERT(!outputDesc->isDuplicated(),
545 "updateCallRouting() RX device output is duplicated");
546 outputDesc->toAudioPortConfig(&patch.sources[1]);
547 patch.num_sources = 2;
548 }
549
550 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
551 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
552 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
553 status);
554 if (status == NO_ERROR) {
555 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
556 &patch, mUidCached);
557 mCallRxPatch->mAfPatchHandle = afPatchHandle;
558 mCallRxPatch->mUid = mUidCached;
559 }
560 createTxPatch = true;
561 }
562 if (createTxPatch) {
563
564 struct audio_patch patch;
565 patch.num_sources = 1;
566 patch.num_sinks = 1;
567 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
568 ALOG_ASSERT(!deviceList.isEmpty(),
569 "updateCallRouting() selected device not in input device list");
570 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
571 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
572 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
573 ALOG_ASSERT(!deviceList.isEmpty(),
574 "updateCallRouting() no telephony TX device");
575 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
576 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
577
578 SortedVector<audio_io_handle_t> outputs =
579 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700580 audio_io_handle_t output = selectOutput(outputs,
581 AUDIO_OUTPUT_FLAG_NONE,
582 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700583 // request to reuse existing output stream if one is already opened to reach the TX
584 // path output device
585 if (output != AUDIO_IO_HANDLE_NONE) {
586 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
587 ALOG_ASSERT(!outputDesc->isDuplicated(),
588 "updateCallRouting() RX device output is duplicated");
589 outputDesc->toAudioPortConfig(&patch.sources[1]);
590 patch.num_sources = 2;
591 }
592
593 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
594 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
595 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
596 status);
597 if (status == NO_ERROR) {
598 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
599 &patch, mUidCached);
600 mCallTxPatch->mAfPatchHandle = afPatchHandle;
601 mCallTxPatch->mUid = mUidCached;
602 }
603 }
604}
605
Eric Laurente0720872014-03-11 09:30:41 -0700606void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700607{
608 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700609 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700610 ALOGW("setPhoneState() invalid state %d", state);
611 return;
612 }
613
614 if (state == mPhoneState ) {
615 ALOGW("setPhoneState() setting same state %d", state);
616 return;
617 }
618
619 // if leaving call state, handle special case of active streams
620 // pertaining to sonification strategy see handleIncallSonification()
621 if (isInCall()) {
622 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700623 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800624 if (stream == AUDIO_STREAM_PATCH) {
625 continue;
626 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700627 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700628 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800629
630 // force reevaluating accessibility routing when call starts
631 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700632 }
633
634 // store previous phone state for management of sonification strategy below
635 int oldState = mPhoneState;
636 mPhoneState = state;
637 bool force = false;
638
639 // are we entering or starting a call
640 if (!isStateInCall(oldState) && isStateInCall(state)) {
641 ALOGV(" Entering call in setPhoneState()");
642 // force routing command to audio hardware when starting a call
643 // even if no device change is needed
644 force = true;
645 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
646 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
647 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
648 }
649 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
650 ALOGV(" Exiting call in setPhoneState()");
651 // force routing command to audio hardware when exiting a call
652 // even if no device change is needed
653 force = true;
654 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
655 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
656 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
657 }
658 } else if (isStateInCall(state) && (state != oldState)) {
659 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
660 // force routing command to audio hardware when switching between telephony and VoIP
661 // even if no device change is needed
662 force = true;
663 }
664
665 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700666 checkA2dpSuspend();
667 checkOutputForAllStrategies();
668 updateDevicesAndOutputs();
669
Eric Laurent1f2f2232014-06-02 12:01:23 -0700670 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700671
Eric Laurente552edb2014-03-10 17:42:56 -0700672 int delayMs = 0;
673 if (isStateInCall(state)) {
674 nsecs_t sysTime = systemTime();
675 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700676 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700677 // mute media and sonification strategies and delay device switch by the largest
678 // latency of any output where either strategy is active.
679 // This avoid sending the ring tone or music tail into the earpiece or headset.
680 if ((desc->isStrategyActive(STRATEGY_MEDIA,
681 SONIFICATION_HEADSET_MUSIC_DELAY,
682 sysTime) ||
683 desc->isStrategyActive(STRATEGY_SONIFICATION,
684 SONIFICATION_HEADSET_MUSIC_DELAY,
685 sysTime)) &&
686 (delayMs < (int)desc->mLatency*2)) {
687 delayMs = desc->mLatency*2;
688 }
689 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
690 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
691 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
692 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
693 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
694 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
695 }
696 }
697
Eric Laurentc2730ba2014-07-20 15:47:07 -0700698 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
699 // the device returned is not necessarily reachable via this output
700 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
701 // force routing command to audio hardware when ending call
702 // even if no device change is needed
703 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
704 rxDevice = hwOutputDesc->device();
705 }
Eric Laurente552edb2014-03-10 17:42:56 -0700706
Eric Laurentc2730ba2014-07-20 15:47:07 -0700707 if (state == AUDIO_MODE_IN_CALL) {
708 updateCallRouting(rxDevice, delayMs);
709 } else if (oldState == AUDIO_MODE_IN_CALL) {
710 if (mCallRxPatch != 0) {
711 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
712 mCallRxPatch.clear();
713 }
714 if (mCallTxPatch != 0) {
715 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
716 mCallTxPatch.clear();
717 }
718 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
719 } else {
720 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
721 }
Eric Laurente552edb2014-03-10 17:42:56 -0700722 // if entering in call state, handle special case of active streams
723 // pertaining to sonification strategy see handleIncallSonification()
724 if (isStateInCall(state)) {
725 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700726 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800727 if (stream == AUDIO_STREAM_PATCH) {
728 continue;
729 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700730 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700731 }
732 }
733
734 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700735 if (state == AUDIO_MODE_RINGTONE &&
736 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700737 mLimitRingtoneVolume = true;
738 } else {
739 mLimitRingtoneVolume = false;
740 }
741}
742
Eric Laurente0720872014-03-11 09:30:41 -0700743void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700744 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700745{
746 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
747
748 bool forceVolumeReeval = false;
749 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700750 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
751 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
752 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700753 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
754 return;
755 }
756 forceVolumeReeval = true;
757 mForceUse[usage] = config;
758 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700759 case AUDIO_POLICY_FORCE_FOR_MEDIA:
760 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
761 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
762 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
763 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Hochi Huang327cb702014-09-21 09:47:31 +0800764 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
Eric Laurente552edb2014-03-10 17:42:56 -0700765 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
766 return;
767 }
768 mForceUse[usage] = config;
769 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700770 case AUDIO_POLICY_FORCE_FOR_RECORD:
771 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
772 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700773 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
774 return;
775 }
776 mForceUse[usage] = config;
777 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700778 case AUDIO_POLICY_FORCE_FOR_DOCK:
779 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
780 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
781 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
782 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
783 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700784 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
785 }
786 forceVolumeReeval = true;
787 mForceUse[usage] = config;
788 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700789 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
790 if (config != AUDIO_POLICY_FORCE_NONE &&
791 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700792 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
793 }
794 forceVolumeReeval = true;
795 mForceUse[usage] = config;
796 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900797 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
798 if (config != AUDIO_POLICY_FORCE_NONE &&
799 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
800 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
801 }
802 mForceUse[usage] = config;
803 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700804 default:
805 ALOGW("setForceUse() invalid usage %d", usage);
806 break;
807 }
808
809 // check for device and output changes triggered by new force usage
810 checkA2dpSuspend();
811 checkOutputForAllStrategies();
812 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700813 if (mPhoneState == AUDIO_MODE_IN_CALL) {
814 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
815 updateCallRouting(newDevice);
816 }
Eric Laurente552edb2014-03-10 17:42:56 -0700817 for (size_t i = 0; i < mOutputs.size(); i++) {
818 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700819 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700820 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
821 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
822 }
Eric Laurente552edb2014-03-10 17:42:56 -0700823 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
824 applyStreamVolumes(output, newDevice, 0, true);
825 }
826 }
827
828 audio_io_handle_t activeInput = getActiveInput();
829 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700830 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700831 }
832
833}
834
Eric Laurente0720872014-03-11 09:30:41 -0700835audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700836{
837 return mForceUse[usage];
838}
839
Eric Laurente0720872014-03-11 09:30:41 -0700840void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700841{
842 ALOGV("setSystemProperty() property %s, value %s", property, value);
843}
844
845// Find a direct output profile compatible with the parameters passed, even if the input flags do
846// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700847sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700848 audio_devices_t device,
849 uint32_t samplingRate,
850 audio_format_t format,
851 audio_channel_mask_t channelMask,
852 audio_output_flags_t flags)
853{
854 for (size_t i = 0; i < mHwModules.size(); i++) {
855 if (mHwModules[i]->mHandle == 0) {
856 continue;
857 }
858 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700859 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent275e8e92014-11-30 15:14:47 -0800860 bool found = profile->isCompatibleProfile(device, String8(""), samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -0700861 NULL /*updatedSamplingRate*/, format, channelMask,
862 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
863 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700864 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
865 return profile;
866 }
Eric Laurente552edb2014-03-10 17:42:56 -0700867 }
868 }
869 return 0;
870}
871
Eric Laurente0720872014-03-11 09:30:41 -0700872audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700873 uint32_t samplingRate,
874 audio_format_t format,
875 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700876 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700877 const audio_offload_info_t *offloadInfo)
878{
Eric Laurent3b73df72014-03-11 09:06:29 -0700879 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700880 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
881 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
882 device, stream, samplingRate, format, channelMask, flags);
883
Eric Laurente83b55d2014-11-14 10:06:21 -0800884 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
885 stream, samplingRate,format, channelMask,
886 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700887}
888
Eric Laurente83b55d2014-11-14 10:06:21 -0800889status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
890 audio_io_handle_t *output,
891 audio_session_t session,
892 audio_stream_type_t *stream,
893 uint32_t samplingRate,
894 audio_format_t format,
895 audio_channel_mask_t channelMask,
896 audio_output_flags_t flags,
897 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700898{
Eric Laurente83b55d2014-11-14 10:06:21 -0800899 audio_attributes_t attributes;
900 if (attr != NULL) {
901 if (!isValidAttributes(attr)) {
902 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
903 attr->usage, attr->content_type, attr->flags,
904 attr->tags);
905 return BAD_VALUE;
906 }
907 attributes = *attr;
908 } else {
909 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
910 ALOGE("getOutputForAttr(): invalid stream type");
911 return BAD_VALUE;
912 }
913 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700914 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800915
Eric Laurent275e8e92014-11-30 15:14:47 -0800916 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
917 sp<AudioOutputDescriptor> desc;
918 if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_PLAYERS) {
919 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
920 if ((RULE_MATCH_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
921 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage == attributes.usage) ||
922 (RULE_EXCLUDE_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
923 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage != attributes.usage)) {
924 desc = mPolicyMixes[i]->mOutput;
925 break;
926 }
927 if (strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
928 strncmp(attributes.tags + strlen("addr="),
929 mPolicyMixes[i]->mMix.mRegistrationId.string(),
930 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
931 desc = mPolicyMixes[i]->mOutput;
932 break;
933 }
934 }
935 } else if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_RECORDERS) {
936 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE &&
937 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
938 strncmp(attributes.tags + strlen("addr="),
939 mPolicyMixes[i]->mMix.mRegistrationId.string(),
940 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
941 desc = mPolicyMixes[i]->mOutput;
Eric Laurent275e8e92014-11-30 15:14:47 -0800942 }
943 }
944 if (desc != 0) {
945 if (!audio_is_linear_pcm(format)) {
946 return BAD_VALUE;
947 }
Eric Laurentc722f302014-12-10 11:21:49 -0800948 desc->mPolicyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -0800949 *stream = streamTypefromAttributesInt(&attributes);
950 *output = desc->mIoHandle;
951 ALOGV("getOutputForAttr() returns output %d", *output);
952 return NO_ERROR;
953 }
954 }
955 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
956 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
957 return BAD_VALUE;
958 }
959
Eric Laurent93c3d412014-08-01 14:48:35 -0700960 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800961 attributes.usage, attributes.content_type, attributes.tags, attributes.flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700962
Eric Laurente83b55d2014-11-14 10:06:21 -0800963 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700964 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700965
Eric Laurente83b55d2014-11-14 10:06:21 -0800966 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700967 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
968 }
969
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700970 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700971 device, samplingRate, format, channelMask, flags);
972
Eric Laurente83b55d2014-11-14 10:06:21 -0800973 *stream = streamTypefromAttributesInt(&attributes);
974 *output = getOutputForDevice(device, session, *stream,
975 samplingRate, format, channelMask,
976 flags, offloadInfo);
977 if (*output == AUDIO_IO_HANDLE_NONE) {
978 return INVALID_OPERATION;
979 }
980 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700981}
982
983audio_io_handle_t AudioPolicyManager::getOutputForDevice(
984 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800985 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700986 audio_stream_type_t stream,
987 uint32_t samplingRate,
988 audio_format_t format,
989 audio_channel_mask_t channelMask,
990 audio_output_flags_t flags,
991 const audio_offload_info_t *offloadInfo)
992{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700993 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700994 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700995 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700996
Eric Laurente552edb2014-03-10 17:42:56 -0700997#ifdef AUDIO_POLICY_TEST
998 if (mCurOutput != 0) {
999 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
1000 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
1001
1002 if (mTestOutputs[mCurOutput] == 0) {
1003 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -07001004 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07001005 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -07001006 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -07001007 outputDesc->mFlags =
1008 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001009 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001010 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1011 config.sample_rate = mTestSamplingRate;
1012 config.channel_mask = mTestChannels;
1013 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -07001014 if (offloadInfo != NULL) {
1015 config.offload_info = *offloadInfo;
1016 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001017 status = mpClientInterface->openOutput(0,
1018 &mTestOutputs[mCurOutput],
1019 &config,
1020 &outputDesc->mDevice,
1021 String8(""),
1022 &outputDesc->mLatency,
1023 outputDesc->mFlags);
1024 if (status == NO_ERROR) {
1025 outputDesc->mSamplingRate = config.sample_rate;
1026 outputDesc->mFormat = config.format;
1027 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -07001028 AudioParameter outputCmd = AudioParameter();
1029 outputCmd.addInt(String8("set_id"),mCurOutput);
1030 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
1031 addOutput(mTestOutputs[mCurOutput], outputDesc);
1032 }
1033 }
1034 return mTestOutputs[mCurOutput];
1035 }
1036#endif //AUDIO_POLICY_TEST
1037
1038 // open a direct output if required by specified parameters
1039 //force direct flag if offload flag is set: offloading implies a direct output stream
1040 // and all common behaviors are driven by checking only the direct flag
1041 // this should normally be set appropriately in the policy configuration file
1042 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07001043 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001044 }
Eric Laurent93c3d412014-08-01 14:48:35 -07001045 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1046 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
1047 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001048 // only allow deep buffering for music stream type
1049 if (stream != AUDIO_STREAM_MUSIC) {
1050 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1051 }
Eric Laurente552edb2014-03-10 17:42:56 -07001052
Eric Laurentb732cf52014-09-24 19:08:21 -07001053 sp<IOProfile> profile;
1054
1055 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001056 // and not explicitly requested
1057 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1058 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -07001059 audio_channel_count_from_out_mask(channelMask) <= 2) {
1060 goto non_direct_output;
1061 }
1062
Eric Laurente552edb2014-03-10 17:42:56 -07001063 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1064 // creating an offloaded track and tearing it down immediately after start when audioflinger
1065 // detects there is an active non offloadable effect.
1066 // FIXME: We should check the audio session here but we do not have it in this context.
1067 // This may prevent offloading in rare situations where effects are left active by apps
1068 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001069
Eric Laurente552edb2014-03-10 17:42:56 -07001070 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1071 !isNonOffloadableEffectEnabled()) {
1072 profile = getProfileForDirectOutput(device,
1073 samplingRate,
1074 format,
1075 channelMask,
1076 (audio_output_flags_t)flags);
1077 }
1078
Eric Laurent1c333e22014-05-20 10:48:17 -07001079 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001080 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -07001081
1082 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001083 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001084 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1085 outputDesc = desc;
1086 // reuse direct output if currently open and configured with same parameters
1087 if ((samplingRate == outputDesc->mSamplingRate) &&
1088 (format == outputDesc->mFormat) &&
1089 (channelMask == outputDesc->mChannelMask)) {
1090 outputDesc->mDirectOpenCount++;
1091 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
1092 return mOutputs.keyAt(i);
1093 }
1094 }
1095 }
1096 // close direct output if currently open and configured with different parameters
1097 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001098 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001099 }
1100 outputDesc = new AudioOutputDescriptor(profile);
1101 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001102 outputDesc->mLatency = 0;
1103 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001104 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1105 config.sample_rate = samplingRate;
1106 config.channel_mask = channelMask;
1107 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001108 if (offloadInfo != NULL) {
1109 config.offload_info = *offloadInfo;
1110 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001111 status = mpClientInterface->openOutput(profile->mModule->mHandle,
1112 &output,
1113 &config,
1114 &outputDesc->mDevice,
1115 String8(""),
1116 &outputDesc->mLatency,
1117 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001118
1119 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001120 if (status != NO_ERROR ||
1121 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1122 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1123 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001124 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1125 "format %d %d, channelMask %04x %04x", output, samplingRate,
1126 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1127 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001128 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001129 mpClientInterface->closeOutput(output);
1130 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001131 // fall back to mixer output if possible when the direct output could not be open
1132 if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE) {
1133 goto non_direct_output;
1134 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001135 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001136 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001137 outputDesc->mSamplingRate = config.sample_rate;
1138 outputDesc->mChannelMask = config.channel_mask;
1139 outputDesc->mFormat = config.format;
1140 outputDesc->mRefCount[stream] = 0;
1141 outputDesc->mStopTime[stream] = 0;
1142 outputDesc->mDirectOpenCount = 1;
1143
Eric Laurente552edb2014-03-10 17:42:56 -07001144 audio_io_handle_t srcOutput = getOutputForEffect();
1145 addOutput(output, outputDesc);
1146 audio_io_handle_t dstOutput = getOutputForEffect();
1147 if (dstOutput == output) {
1148 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1149 }
1150 mPreviousOutputs = mOutputs;
1151 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001152 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001153 return output;
1154 }
1155
Eric Laurentb732cf52014-09-24 19:08:21 -07001156non_direct_output:
1157
Eric Laurente552edb2014-03-10 17:42:56 -07001158 // ignoring channel mask due to downmix capability in mixer
1159
1160 // open a non direct output
1161
1162 // for non direct outputs, only PCM is supported
1163 if (audio_is_linear_pcm(format)) {
1164 // get which output is suitable for the specified stream. The actual
1165 // routing change will happen when startOutput() will be called
1166 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1167
Eric Laurent8838a382014-09-08 16:44:28 -07001168 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1169 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1170 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001171 }
1172 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1173 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1174
1175 ALOGV("getOutput() returns output %d", output);
1176
1177 return output;
1178}
1179
Eric Laurente0720872014-03-11 09:30:41 -07001180audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001181 audio_output_flags_t flags,
1182 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001183{
1184 // select one output among several that provide a path to a particular device or set of
1185 // devices (the list was previously build by getOutputsForDevice()).
1186 // The priority is as follows:
1187 // 1: the output with the highest number of requested policy flags
1188 // 2: the primary output
1189 // 3: the first output in the list
1190
1191 if (outputs.size() == 0) {
1192 return 0;
1193 }
1194 if (outputs.size() == 1) {
1195 return outputs[0];
1196 }
1197
1198 int maxCommonFlags = 0;
1199 audio_io_handle_t outputFlags = 0;
1200 audio_io_handle_t outputPrimary = 0;
1201
1202 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001203 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001204 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001205 // if a valid format is specified, skip output if not compatible
1206 if (format != AUDIO_FORMAT_INVALID) {
1207 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1208 if (format != outputDesc->mFormat) {
1209 continue;
1210 }
1211 } else if (!audio_is_linear_pcm(format)) {
1212 continue;
1213 }
1214 }
1215
Eric Laurent3b73df72014-03-11 09:06:29 -07001216 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001217 if (commonFlags > maxCommonFlags) {
1218 outputFlags = outputs[i];
1219 maxCommonFlags = commonFlags;
1220 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1221 }
1222 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1223 outputPrimary = outputs[i];
1224 }
1225 }
1226 }
1227
1228 if (outputFlags != 0) {
1229 return outputFlags;
1230 }
1231 if (outputPrimary != 0) {
1232 return outputPrimary;
1233 }
1234
1235 return outputs[0];
1236}
1237
Eric Laurente0720872014-03-11 09:30:41 -07001238status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001239 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001240 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001241{
1242 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1243 ssize_t index = mOutputs.indexOfKey(output);
1244 if (index < 0) {
1245 ALOGW("startOutput() unknown output %d", output);
1246 return BAD_VALUE;
1247 }
1248
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001249 // cannot start playback of STREAM_TTS if any other output is being used
1250 uint32_t beaconMuteLatency = 0;
1251 if (stream == AUDIO_STREAM_TTS) {
1252 ALOGV("\t found BEACON stream");
1253 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1254 return INVALID_OPERATION;
1255 } else {
1256 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1257 }
1258 } else {
1259 // some playback other than beacon starts
1260 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1261 }
1262
Eric Laurent1f2f2232014-06-02 12:01:23 -07001263 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001264
1265 // increment usage count for this stream on the requested output:
1266 // NOTE that the usage count is the same for duplicated output and hardware output which is
1267 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1268 outputDesc->changeRefCount(stream, 1);
1269
1270 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001271 // starting an output being rerouted?
1272 audio_devices_t newDevice;
Eric Laurentc722f302014-12-10 11:21:49 -08001273 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001274 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1275 } else {
1276 newDevice = getNewOutputDevice(output, false /*fromCache*/);
1277 }
Eric Laurente552edb2014-03-10 17:42:56 -07001278 routing_strategy strategy = getStrategy(stream);
1279 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001280 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1281 (beaconMuteLatency > 0);
1282 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001283 bool force = false;
1284 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001285 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001286 if (desc != outputDesc) {
1287 // force a device change if any other output is managed by the same hw
1288 // module and has a current device selection that differs from selected device.
1289 // In this case, the audio HAL must receive the new device selection so that it can
1290 // change the device currently selected by the other active output.
1291 if (outputDesc->sharesHwModuleWith(desc) &&
1292 desc->device() != newDevice) {
1293 force = true;
1294 }
1295 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001296 // a notification so that audio focus effect can propagate, or that a mute/unmute
1297 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001298 uint32_t latency = desc->latency();
1299 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1300 waitMs = latency;
1301 }
1302 }
1303 }
1304 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1305
1306 // handle special case for sonification while in call
1307 if (isInCall()) {
1308 handleIncallSonification(stream, true, false);
1309 }
1310
1311 // apply volume rules for current stream and device if necessary
1312 checkAndSetVolume(stream,
1313 mStreams[stream].getVolumeIndex(newDevice),
1314 output,
1315 newDevice);
1316
1317 // update the outputs if starting an output with a stream that can affect notification
1318 // routing
1319 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001320
1321 // Automatically enable the remote submix input when output is started on a re routing mix
1322 // of type MIX_TYPE_RECORDERS
1323 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1324 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001325 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001326 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001327 outputDesc->mPolicyMix->mRegistrationId,
1328 "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001329 }
1330
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001331 // force reevaluating accessibility routing when ringtone or alarm starts
1332 if (strategy == STRATEGY_SONIFICATION) {
1333 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1334 }
1335
Eric Laurente552edb2014-03-10 17:42:56 -07001336 if (waitMs > muteWaitMs) {
1337 usleep((waitMs - muteWaitMs) * 2 * 1000);
1338 }
1339 }
1340 return NO_ERROR;
1341}
1342
1343
Eric Laurente0720872014-03-11 09:30:41 -07001344status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001345 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001346 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001347{
1348 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1349 ssize_t index = mOutputs.indexOfKey(output);
1350 if (index < 0) {
1351 ALOGW("stopOutput() unknown output %d", output);
1352 return BAD_VALUE;
1353 }
1354
Eric Laurent1f2f2232014-06-02 12:01:23 -07001355 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001356
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001357 // always handle stream stop, check which stream type is stopping
1358 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1359
Eric Laurente552edb2014-03-10 17:42:56 -07001360 // handle special case for sonification while in call
1361 if (isInCall()) {
1362 handleIncallSonification(stream, false, false);
1363 }
1364
1365 if (outputDesc->mRefCount[stream] > 0) {
1366 // decrement usage count of this stream on the output
1367 outputDesc->changeRefCount(stream, -1);
1368 // store time at which the stream was stopped - see isStreamActive()
1369 if (outputDesc->mRefCount[stream] == 0) {
Eric Laurentc722f302014-12-10 11:21:49 -08001370 // Automatically disable the remote submix input when output is stopped on a
1371 // re routing mix of type MIX_TYPE_RECORDERS
1372 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1373 outputDesc->mPolicyMix != NULL &&
1374 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001375 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001376 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001377 outputDesc->mPolicyMix->mRegistrationId,
1378 "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001379 }
1380
Eric Laurente552edb2014-03-10 17:42:56 -07001381 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001382 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001383 // delay the device switch by twice the latency because stopOutput() is executed when
1384 // the track stop() command is received and at that time the audio track buffer can
1385 // still contain data that needs to be drained. The latency only covers the audio HAL
1386 // and kernel buffers. Also the latency does not always include additional delay in the
1387 // audio path (audio DSP, CODEC ...)
1388 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1389
1390 // force restoring the device selection on other active outputs if it differs from the
1391 // one being selected for this output
1392 for (size_t i = 0; i < mOutputs.size(); i++) {
1393 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001394 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001395 if (curOutput != output &&
1396 desc->isActive() &&
1397 outputDesc->sharesHwModuleWith(desc) &&
1398 (newDevice != desc->device())) {
1399 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001400 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001401 true,
1402 outputDesc->mLatency*2);
1403 }
1404 }
1405 // update the outputs if stopping one with a stream that can affect notification routing
1406 handleNotificationRoutingForStream(stream);
1407 }
1408 return NO_ERROR;
1409 } else {
1410 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1411 return INVALID_OPERATION;
1412 }
1413}
1414
Eric Laurente83b55d2014-11-14 10:06:21 -08001415void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001416 audio_stream_type_t stream __unused,
1417 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001418{
1419 ALOGV("releaseOutput() %d", output);
1420 ssize_t index = mOutputs.indexOfKey(output);
1421 if (index < 0) {
1422 ALOGW("releaseOutput() releasing unknown output %d", output);
1423 return;
1424 }
1425
1426#ifdef AUDIO_POLICY_TEST
1427 int testIndex = testOutputIndex(output);
1428 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001429 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001430 if (outputDesc->isActive()) {
1431 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001432 mOutputs.removeItem(output);
1433 mTestOutputs[testIndex] = 0;
1434 }
1435 return;
1436 }
1437#endif //AUDIO_POLICY_TEST
1438
Eric Laurent1f2f2232014-06-02 12:01:23 -07001439 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001440 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001441 if (desc->mDirectOpenCount <= 0) {
1442 ALOGW("releaseOutput() invalid open count %d for output %d",
1443 desc->mDirectOpenCount, output);
1444 return;
1445 }
1446 if (--desc->mDirectOpenCount == 0) {
1447 closeOutput(output);
1448 // If effects where present on the output, audioflinger moved them to the primary
1449 // output by default: move them back to the appropriate output.
1450 audio_io_handle_t dstOutput = getOutputForEffect();
1451 if (dstOutput != mPrimaryOutput) {
1452 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1453 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001454 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001455 }
1456 }
1457}
1458
1459
Eric Laurentcaf7f482014-11-25 17:50:47 -08001460status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1461 audio_io_handle_t *input,
1462 audio_session_t session,
1463 uint32_t samplingRate,
1464 audio_format_t format,
1465 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001466 audio_input_flags_t flags,
1467 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001468{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001469 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1470 "session %d, flags %#x",
1471 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001472
Eric Laurentcaf7f482014-11-25 17:50:47 -08001473 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001474 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001475 audio_devices_t device;
1476 // handle legacy remote submix case where the address was not always specified
1477 String8 address = String8("");
Eric Laurent5dbe4712014-09-19 19:04:57 -07001478 bool isSoundTrigger = false;
Eric Laurentc447ded2015-01-06 08:47:05 -08001479 audio_source_t inputSource = attr->source;
1480 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001481 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001482
Eric Laurentc447ded2015-01-06 08:47:05 -08001483 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1484 inputSource = AUDIO_SOURCE_MIC;
1485 }
1486 halInputSource = inputSource;
1487
1488 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001489 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
1490 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1491 address = String8(attr->tags + strlen("addr="));
1492 ssize_t index = mPolicyMixes.indexOfKey(address);
1493 if (index < 0) {
1494 ALOGW("getInputForAttr() no policy for address %s", address.string());
1495 return BAD_VALUE;
1496 }
Eric Laurentc722f302014-12-10 11:21:49 -08001497 if (mPolicyMixes[index]->mMix.mMixType != MIX_TYPE_PLAYERS) {
1498 ALOGW("getInputForAttr() bad policy mix type for address %s", address.string());
1499 return BAD_VALUE;
1500 }
1501 policyMix = &mPolicyMixes[index]->mMix;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001502 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001503 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001504 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001505 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001506 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001507 return BAD_VALUE;
1508 }
Eric Laurentc722f302014-12-10 11:21:49 -08001509 if (policyMix != NULL) {
1510 address = policyMix->mRegistrationId;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001511 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1512 // there is an external policy, but this input is attached to a mix of recorders,
1513 // meaning it receives audio injected into the framework, so the recorder doesn't
1514 // know about it and is therefore considered "legacy"
1515 *inputType = API_INPUT_LEGACY;
1516 } else {
1517 // recording a mix of players defined by an external policy, we're rerouting for
1518 // an external policy
1519 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1520 }
Eric Laurentc722f302014-12-10 11:21:49 -08001521 } else if (audio_is_remote_submix_device(device)) {
1522 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001523 *inputType = API_INPUT_MIX_CAPTURE;
1524 } else {
1525 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001526 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001527 // adapt channel selection to input source
Eric Laurentc447ded2015-01-06 08:47:05 -08001528 switch (inputSource) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001529 case AUDIO_SOURCE_VOICE_UPLINK:
1530 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1531 break;
1532 case AUDIO_SOURCE_VOICE_DOWNLINK:
1533 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1534 break;
1535 case AUDIO_SOURCE_VOICE_CALL:
1536 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1537 break;
1538 default:
1539 break;
1540 }
Eric Laurentc447ded2015-01-06 08:47:05 -08001541 if (inputSource == AUDIO_SOURCE_HOTWORD) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001542 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1543 if (index >= 0) {
1544 *input = mSoundTriggerSessions.valueFor(session);
1545 isSoundTrigger = true;
1546 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1547 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
1548 } else {
1549 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1550 }
Eric Laurent5dbe4712014-09-19 19:04:57 -07001551 }
1552 }
1553
Eric Laurent275e8e92014-11-30 15:14:47 -08001554 sp<IOProfile> profile = getInputProfile(device, address,
1555 samplingRate, format, channelMask,
1556 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001557 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001558 //retry without flags
1559 audio_input_flags_t log_flags = flags;
1560 flags = AUDIO_INPUT_FLAG_NONE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001561 profile = getInputProfile(device, address,
1562 samplingRate, format, channelMask,
1563 flags);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001564 if (profile == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001565 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1566 "format %#x, channelMask 0x%X, flags %#x",
Eric Laurent5dbe4712014-09-19 19:04:57 -07001567 device, samplingRate, format, channelMask, log_flags);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001568 return BAD_VALUE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001569 }
Eric Laurente552edb2014-03-10 17:42:56 -07001570 }
1571
1572 if (profile->mModule->mHandle == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001573 ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName);
1574 return NO_INIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001575 }
1576
1577 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1578 config.sample_rate = samplingRate;
1579 config.channel_mask = channelMask;
1580 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001581
Eric Laurentcf2c0212014-07-25 16:20:43 -07001582 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001583 input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001584 &config,
1585 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001586 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001587 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001588 flags);
1589
1590 // only accept input with the exact requested set of parameters
Eric Laurentcaf7f482014-11-25 17:50:47 -08001591 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001592 (samplingRate != config.sample_rate) ||
1593 (format != config.format) ||
1594 (channelMask != config.channel_mask)) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001595 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001596 samplingRate, format, channelMask);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001597 if (*input != AUDIO_IO_HANDLE_NONE) {
1598 mpClientInterface->closeInput(*input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001599 }
Eric Laurentcaf7f482014-11-25 17:50:47 -08001600 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001601 }
1602
Eric Laurent1f2f2232014-06-02 12:01:23 -07001603 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurentc447ded2015-01-06 08:47:05 -08001604 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001605 inputDesc->mRefCount = 0;
1606 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001607 inputDesc->mSamplingRate = samplingRate;
1608 inputDesc->mFormat = format;
1609 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001610 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001611 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001612 inputDesc->mIsSoundTrigger = isSoundTrigger;
Eric Laurentc722f302014-12-10 11:21:49 -08001613 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001614
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001615 ALOGV("getInputForAttr() returns input type = %d", inputType);
1616
Eric Laurentcaf7f482014-11-25 17:50:47 -08001617 addInput(*input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001618 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcaf7f482014-11-25 17:50:47 -08001619 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001620}
1621
Eric Laurent4dc68062014-07-28 17:26:49 -07001622status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1623 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001624{
1625 ALOGV("startInput() input %d", input);
1626 ssize_t index = mInputs.indexOfKey(input);
1627 if (index < 0) {
1628 ALOGW("startInput() unknown input %d", input);
1629 return BAD_VALUE;
1630 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001631 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001632
Eric Laurentc722f302014-12-10 11:21:49 -08001633 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001634 if (index < 0) {
1635 ALOGW("startInput() unknown session %d on input %d", session, input);
1636 return BAD_VALUE;
1637 }
1638
Glenn Kasten74a8e252014-07-24 14:09:55 -07001639 // virtual input devices are compatible with other input devices
1640 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1641
1642 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001643 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001644 if (activeInput != 0 && activeInput != input) {
1645
1646 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1647 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001648 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001649 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001650 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurentc722f302014-12-10 11:21:49 -08001651 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1652 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001653 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001654 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001655 return INVALID_OPERATION;
1656 }
1657 }
1658 }
1659
Glenn Kasten74a8e252014-07-24 14:09:55 -07001660 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001661 if (activeInputsCount() == 0) {
1662 SoundTrigger::setCaptureState(true);
1663 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001664 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001665
Eric Laurentc722f302014-12-10 11:21:49 -08001666 // automatically enable the remote submix output when input is started if not
1667 // used by a policy mix of type MIX_TYPE_RECORDERS
Glenn Kasten74a8e252014-07-24 14:09:55 -07001668 // For remote submix (a virtual device), we open only one input per capture request.
1669 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001670 String8 address = String8("");
1671 if (inputDesc->mPolicyMix == NULL) {
1672 address = String8("0");
1673 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1674 address = inputDesc->mPolicyMix->mRegistrationId;
1675 }
1676 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001677 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001678 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001679 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001680 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001681 }
Eric Laurente552edb2014-03-10 17:42:56 -07001682 }
1683
Eric Laurente552edb2014-03-10 17:42:56 -07001684 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1685
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001686 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001687 return NO_ERROR;
1688}
1689
Eric Laurent4dc68062014-07-28 17:26:49 -07001690status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1691 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001692{
1693 ALOGV("stopInput() input %d", input);
1694 ssize_t index = mInputs.indexOfKey(input);
1695 if (index < 0) {
1696 ALOGW("stopInput() unknown input %d", input);
1697 return BAD_VALUE;
1698 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001699 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001700
Eric Laurentc722f302014-12-10 11:21:49 -08001701 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001702 if (index < 0) {
1703 ALOGW("stopInput() unknown session %d on input %d", session, input);
1704 return BAD_VALUE;
1705 }
1706
Eric Laurente552edb2014-03-10 17:42:56 -07001707 if (inputDesc->mRefCount == 0) {
1708 ALOGW("stopInput() input %d already stopped", input);
1709 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001710 }
1711
1712 inputDesc->mRefCount--;
1713 if (inputDesc->mRefCount == 0) {
1714
Eric Laurentc722f302014-12-10 11:21:49 -08001715 // automatically disable the remote submix output when input is stopped if not
1716 // used by a policy mix of type MIX_TYPE_RECORDERS
Eric Laurente552edb2014-03-10 17:42:56 -07001717 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001718 String8 address = String8("");
1719 if (inputDesc->mPolicyMix == NULL) {
1720 address = String8("0");
1721 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1722 address = inputDesc->mPolicyMix->mRegistrationId;
1723 }
1724 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001725 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001726 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001727 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001728 }
Eric Laurente552edb2014-03-10 17:42:56 -07001729 }
1730
Eric Laurent1c333e22014-05-20 10:48:17 -07001731 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001732
1733 if (activeInputsCount() == 0) {
1734 SoundTrigger::setCaptureState(false);
1735 }
Eric Laurente552edb2014-03-10 17:42:56 -07001736 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001737 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001738}
1739
Eric Laurent4dc68062014-07-28 17:26:49 -07001740void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1741 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001742{
1743 ALOGV("releaseInput() %d", input);
1744 ssize_t index = mInputs.indexOfKey(input);
1745 if (index < 0) {
1746 ALOGW("releaseInput() releasing unknown input %d", input);
1747 return;
1748 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001749 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1750 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001751
Eric Laurentc722f302014-12-10 11:21:49 -08001752 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001753 if (index < 0) {
1754 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1755 return;
1756 }
Eric Laurentc722f302014-12-10 11:21:49 -08001757 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001758 if (inputDesc->mOpenRefCount == 0) {
1759 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1760 return;
1761 }
1762 inputDesc->mOpenRefCount--;
1763 if (inputDesc->mOpenRefCount > 0) {
1764 ALOGV("releaseInput() exit > 0");
1765 return;
1766 }
1767
Eric Laurent05b90f82014-08-27 15:32:29 -07001768 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001769 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001770 ALOGV("releaseInput() exit");
1771}
1772
Eric Laurentd4692962014-05-05 18:13:44 -07001773void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001774 bool patchRemoved = false;
1775
Eric Laurentd4692962014-05-05 18:13:44 -07001776 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001777 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1778 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1779 if (patch_index >= 0) {
1780 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1781 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1782 mAudioPatches.removeItemsAt(patch_index);
1783 patchRemoved = true;
1784 }
Eric Laurentd4692962014-05-05 18:13:44 -07001785 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1786 }
1787 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001788 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001789
1790 if (patchRemoved) {
1791 mpClientInterface->onAudioPatchListUpdate();
1792 }
Eric Laurentd4692962014-05-05 18:13:44 -07001793}
1794
Eric Laurente0720872014-03-11 09:30:41 -07001795void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001796 int indexMin,
1797 int indexMax)
1798{
1799 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1800 if (indexMin < 0 || indexMin >= indexMax) {
1801 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1802 return;
1803 }
1804 mStreams[stream].mIndexMin = indexMin;
1805 mStreams[stream].mIndexMax = indexMax;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001806 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1807 if (stream == AUDIO_STREAM_MUSIC) {
1808 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1809 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1810 }
Eric Laurente552edb2014-03-10 17:42:56 -07001811}
1812
Eric Laurente0720872014-03-11 09:30:41 -07001813status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001814 int index,
1815 audio_devices_t device)
1816{
1817
1818 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1819 return BAD_VALUE;
1820 }
1821 if (!audio_is_output_device(device)) {
1822 return BAD_VALUE;
1823 }
1824
1825 // Force max volume if stream cannot be muted
1826 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1827
1828 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1829 stream, device, index);
1830
1831 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1832 // clear all device specific values
1833 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1834 mStreams[stream].mIndexCur.clear();
1835 }
1836 mStreams[stream].mIndexCur.add(device, index);
1837
Eric Laurent31551f82014-10-10 18:21:56 -07001838 // update volume on all outputs whose current device is also selected by the same
1839 // strategy as the device specified by the caller
1840 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001841
1842
1843 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1844 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1845 if (stream == AUDIO_STREAM_MUSIC) {
1846 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1847 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1848 }
1849 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1850 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001851 return NO_ERROR;
1852 }
Eric Laurente552edb2014-03-10 17:42:56 -07001853 status_t status = NO_ERROR;
1854 for (size_t i = 0; i < mOutputs.size(); i++) {
1855 audio_devices_t curDevice =
1856 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001857 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001858 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1859 if (volStatus != NO_ERROR) {
1860 status = volStatus;
1861 }
1862 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001863 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1864 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1865 index, mOutputs.keyAt(i), curDevice);
1866 }
Eric Laurente552edb2014-03-10 17:42:56 -07001867 }
1868 return status;
1869}
1870
Eric Laurente0720872014-03-11 09:30:41 -07001871status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001872 int *index,
1873 audio_devices_t device)
1874{
1875 if (index == NULL) {
1876 return BAD_VALUE;
1877 }
1878 if (!audio_is_output_device(device)) {
1879 return BAD_VALUE;
1880 }
1881 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1882 // the strategy the stream belongs to.
1883 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1884 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1885 }
1886 device = getDeviceForVolume(device);
1887
1888 *index = mStreams[stream].getVolumeIndex(device);
1889 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1890 return NO_ERROR;
1891}
1892
Eric Laurente0720872014-03-11 09:30:41 -07001893audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001894 const SortedVector<audio_io_handle_t>& outputs)
1895{
1896 // select one output among several suitable for global effects.
1897 // The priority is as follows:
1898 // 1: An offloaded output. If the effect ends up not being offloadable,
1899 // AudioFlinger will invalidate the track and the offloaded output
1900 // will be closed causing the effect to be moved to a PCM output.
1901 // 2: A deep buffer output
1902 // 3: the first output in the list
1903
1904 if (outputs.size() == 0) {
1905 return 0;
1906 }
1907
1908 audio_io_handle_t outputOffloaded = 0;
1909 audio_io_handle_t outputDeepBuffer = 0;
1910
1911 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001912 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001913 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001914 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1915 outputOffloaded = outputs[i];
1916 }
1917 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1918 outputDeepBuffer = outputs[i];
1919 }
1920 }
1921
1922 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1923 outputOffloaded, outputDeepBuffer);
1924 if (outputOffloaded != 0) {
1925 return outputOffloaded;
1926 }
1927 if (outputDeepBuffer != 0) {
1928 return outputDeepBuffer;
1929 }
1930
1931 return outputs[0];
1932}
1933
Eric Laurente0720872014-03-11 09:30:41 -07001934audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001935{
1936 // apply simple rule where global effects are attached to the same output as MUSIC streams
1937
Eric Laurent3b73df72014-03-11 09:06:29 -07001938 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001939 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1940 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1941
1942 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1943 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1944 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1945
1946 return output;
1947}
1948
Eric Laurente0720872014-03-11 09:30:41 -07001949status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001950 audio_io_handle_t io,
1951 uint32_t strategy,
1952 int session,
1953 int id)
1954{
1955 ssize_t index = mOutputs.indexOfKey(io);
1956 if (index < 0) {
1957 index = mInputs.indexOfKey(io);
1958 if (index < 0) {
1959 ALOGW("registerEffect() unknown io %d", io);
1960 return INVALID_OPERATION;
1961 }
1962 }
1963
1964 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1965 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1966 desc->name, desc->memoryUsage);
1967 return INVALID_OPERATION;
1968 }
1969 mTotalEffectsMemory += desc->memoryUsage;
1970 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1971 desc->name, io, strategy, session, id);
1972 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1973
Eric Laurent1f2f2232014-06-02 12:01:23 -07001974 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1975 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1976 effectDesc->mIo = io;
1977 effectDesc->mStrategy = (routing_strategy)strategy;
1978 effectDesc->mSession = session;
1979 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001980
Eric Laurent1f2f2232014-06-02 12:01:23 -07001981 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001982
1983 return NO_ERROR;
1984}
1985
Eric Laurente0720872014-03-11 09:30:41 -07001986status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001987{
1988 ssize_t index = mEffects.indexOfKey(id);
1989 if (index < 0) {
1990 ALOGW("unregisterEffect() unknown effect ID %d", id);
1991 return INVALID_OPERATION;
1992 }
1993
Eric Laurent1f2f2232014-06-02 12:01:23 -07001994 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001995
Eric Laurent1f2f2232014-06-02 12:01:23 -07001996 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001997
Eric Laurent1f2f2232014-06-02 12:01:23 -07001998 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001999 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002000 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
2001 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07002002 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002003 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07002004 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002005 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07002006
2007 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07002008
2009 return NO_ERROR;
2010}
2011
Eric Laurente0720872014-03-11 09:30:41 -07002012status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07002013{
2014 ssize_t index = mEffects.indexOfKey(id);
2015 if (index < 0) {
2016 ALOGW("unregisterEffect() unknown effect ID %d", id);
2017 return INVALID_OPERATION;
2018 }
2019
2020 return setEffectEnabled(mEffects.valueAt(index), enabled);
2021}
2022
Eric Laurent1f2f2232014-06-02 12:01:23 -07002023status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07002024{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002025 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07002026 ALOGV("setEffectEnabled(%s) effect already %s",
2027 enabled?"true":"false", enabled?"enabled":"disabled");
2028 return INVALID_OPERATION;
2029 }
2030
2031 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002032 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002033 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002034 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07002035 return INVALID_OPERATION;
2036 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002037 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002038 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
2039 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002040 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07002041 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002042 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
2043 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002044 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002045 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002046 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
2047 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002048 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07002049 return NO_ERROR;
2050}
2051
Eric Laurente0720872014-03-11 09:30:41 -07002052bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07002053{
2054 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002055 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
2056 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
2057 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002058 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002059 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07002060 return true;
2061 }
2062 }
2063 return false;
2064}
2065
Eric Laurente0720872014-03-11 09:30:41 -07002066bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002067{
2068 nsecs_t sysTime = systemTime();
2069 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002070 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07002071 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002072 return true;
2073 }
2074 }
2075 return false;
2076}
2077
Eric Laurente0720872014-03-11 09:30:41 -07002078bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07002079 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002080{
2081 nsecs_t sysTime = systemTime();
2082 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002083 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002084 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002085 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurentc722f302014-12-10 11:21:49 -08002086 // do not consider re routing (when the output is going to a dynamic policy)
2087 // as "remote playback"
2088 if (outputDesc->mPolicyMix == NULL) {
Jean-Michel Trivi1767df72014-12-09 18:11:49 -08002089 return true;
2090 }
Eric Laurente552edb2014-03-10 17:42:56 -07002091 }
2092 }
2093 return false;
2094}
2095
Eric Laurente0720872014-03-11 09:30:41 -07002096bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002097{
2098 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002099 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurenta34c9ce2014-12-19 11:16:32 -08002100 if (inputDescriptor->mRefCount == 0) {
2101 continue;
2102 }
2103 if (inputDescriptor->mInputSource == (int)source) {
Eric Laurente552edb2014-03-10 17:42:56 -07002104 return true;
2105 }
Eric Laurenta34c9ce2014-12-19 11:16:32 -08002106 // AUDIO_SOURCE_HOTWORD is equivalent to AUDIO_SOURCE_VOICE_RECOGNITION only if it
2107 // corresponds to an active capture triggered by a hardware hotword recognition
2108 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) &&
2109 (inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD)) {
2110 // FIXME: we should not assume that the first session is the active one and keep
2111 // activity count per session. Same in startInput().
2112 ssize_t index = mSoundTriggerSessions.indexOfKey(inputDescriptor->mSessions.itemAt(0));
2113 if (index >= 0) {
2114 return true;
2115 }
2116 }
Eric Laurente552edb2014-03-10 17:42:56 -07002117 }
2118 return false;
2119}
2120
Eric Laurent275e8e92014-11-30 15:14:47 -08002121// Register a list of custom mixes with their attributes and format.
2122// When a mix is registered, corresponding input and output profiles are
2123// added to the remote submix hw module. The profile contains only the
2124// parameters (sampling rate, format...) specified by the mix.
2125// The corresponding input remote submix device is also connected.
2126//
2127// When a remote submix device is connected, the address is checked to select the
2128// appropriate profile and the corresponding input or output stream is opened.
2129//
2130// When capture starts, getInputForAttr() will:
2131// - 1 look for a mix matching the address passed in attribtutes tags if any
2132// - 2 if none found, getDeviceForInputSource() will:
2133// - 2.1 look for a mix matching the attributes source
2134// - 2.2 if none found, default to device selection by policy rules
2135// At this time, the corresponding output remote submix device is also connected
2136// and active playback use cases can be transferred to this mix if needed when reconnecting
2137// after AudioTracks are invalidated
2138//
2139// When playback starts, getOutputForAttr() will:
2140// - 1 look for a mix matching the address passed in attribtutes tags if any
2141// - 2 if none found, look for a mix matching the attributes usage
2142// - 3 if none found, default to device and output selection by policy rules.
2143
2144status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2145{
2146 sp<HwModule> module;
2147 for (size_t i = 0; i < mHwModules.size(); i++) {
2148 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2149 mHwModules[i]->mHandle != 0) {
2150 module = mHwModules[i];
2151 break;
2152 }
2153 }
2154
2155 if (module == 0) {
2156 return INVALID_OPERATION;
2157 }
2158
2159 ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
2160
2161 for (size_t i = 0; i < mixes.size(); i++) {
2162 String8 address = mixes[i].mRegistrationId;
2163 ssize_t index = mPolicyMixes.indexOfKey(address);
2164 if (index >= 0) {
2165 ALOGE("registerPolicyMixes(): mix for address %s already registered", address.string());
2166 continue;
2167 }
2168 audio_config_t outputConfig = mixes[i].mFormat;
2169 audio_config_t inputConfig = mixes[i].mFormat;
2170 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2171 // stereo and let audio flinger do the channel conversion if needed.
2172 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2173 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2174 module->addOutputProfile(address, &outputConfig,
2175 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2176 module->addInputProfile(address, &inputConfig,
2177 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2178 sp<AudioPolicyMix> policyMix = new AudioPolicyMix();
2179 policyMix->mMix = mixes[i];
2180 mPolicyMixes.add(address, policyMix);
Eric Laurentc722f302014-12-10 11:21:49 -08002181 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002182 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002183 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002184 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002185 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002186 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002187 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002188 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002189 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002190 }
2191 return NO_ERROR;
2192}
2193
2194status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2195{
2196 sp<HwModule> module;
2197 for (size_t i = 0; i < mHwModules.size(); i++) {
2198 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2199 mHwModules[i]->mHandle != 0) {
2200 module = mHwModules[i];
2201 break;
2202 }
2203 }
2204
2205 if (module == 0) {
2206 return INVALID_OPERATION;
2207 }
2208
2209 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
2210
2211 for (size_t i = 0; i < mixes.size(); i++) {
2212 String8 address = mixes[i].mRegistrationId;
2213 ssize_t index = mPolicyMixes.indexOfKey(address);
2214 if (index < 0) {
2215 ALOGE("unregisterPolicyMixes(): mix for address %s not registered", address.string());
2216 continue;
2217 }
2218
2219 mPolicyMixes.removeItemsAt(index);
2220
Eric Laurentc722f302014-12-10 11:21:49 -08002221 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2222 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2223 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002224 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002225 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002226 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002227 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002228
2229 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2230 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2231 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002232 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08002233 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002234 address.string(), "remote-submix");
Eric Laurent275e8e92014-11-30 15:14:47 -08002235 }
2236 module->removeOutputProfile(address);
2237 module->removeInputProfile(address);
2238 }
2239 return NO_ERROR;
2240}
2241
Eric Laurente552edb2014-03-10 17:42:56 -07002242
Eric Laurente0720872014-03-11 09:30:41 -07002243status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002244{
2245 const size_t SIZE = 256;
2246 char buffer[SIZE];
2247 String8 result;
2248
2249 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2250 result.append(buffer);
2251
2252 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
2253 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002254 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
2255 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002256 snprintf(buffer, SIZE, " Force use for communications %d\n",
2257 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07002258 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002259 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07002260 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002261 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07002262 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002263 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07002264 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002265 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07002266 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002267 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2268 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
2269 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002270
Eric Laurent3a4311c2014-03-17 12:00:47 -07002271 snprintf(buffer, SIZE, " Available output devices:\n");
2272 result.append(buffer);
2273 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002274 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002275 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002276 }
2277 snprintf(buffer, SIZE, "\n Available input devices:\n");
2278 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07002279 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002280 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002281 }
Eric Laurente552edb2014-03-10 17:42:56 -07002282
2283 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
2284 write(fd, buffer, strlen(buffer));
2285 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002286 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002287 write(fd, buffer, strlen(buffer));
2288 mHwModules[i]->dump(fd);
2289 }
2290
2291 snprintf(buffer, SIZE, "\nOutputs dump:\n");
2292 write(fd, buffer, strlen(buffer));
2293 for (size_t i = 0; i < mOutputs.size(); i++) {
2294 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
2295 write(fd, buffer, strlen(buffer));
2296 mOutputs.valueAt(i)->dump(fd);
2297 }
2298
2299 snprintf(buffer, SIZE, "\nInputs dump:\n");
2300 write(fd, buffer, strlen(buffer));
2301 for (size_t i = 0; i < mInputs.size(); i++) {
2302 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
2303 write(fd, buffer, strlen(buffer));
2304 mInputs.valueAt(i)->dump(fd);
2305 }
2306
2307 snprintf(buffer, SIZE, "\nStreams dump:\n");
2308 write(fd, buffer, strlen(buffer));
2309 snprintf(buffer, SIZE,
2310 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
2311 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002312 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002313 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07002314 write(fd, buffer, strlen(buffer));
2315 mStreams[i].dump(fd);
2316 }
2317
2318 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2319 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2320 write(fd, buffer, strlen(buffer));
2321
2322 snprintf(buffer, SIZE, "Registered effects:\n");
2323 write(fd, buffer, strlen(buffer));
2324 for (size_t i = 0; i < mEffects.size(); i++) {
2325 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2326 write(fd, buffer, strlen(buffer));
2327 mEffects.valueAt(i)->dump(fd);
2328 }
2329
Eric Laurent4d416952014-08-10 14:07:09 -07002330 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2331 write(fd, buffer, strlen(buffer));
2332 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2333 mAudioPatches[i]->dump(fd, 2, i);
2334 }
Eric Laurente552edb2014-03-10 17:42:56 -07002335
2336 return NO_ERROR;
2337}
2338
2339// This function checks for the parameters which can be offloaded.
2340// This can be enhanced depending on the capability of the DSP and policy
2341// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002342bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002343{
2344 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002345 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002346 offloadInfo.sample_rate, offloadInfo.channel_mask,
2347 offloadInfo.format,
2348 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2349 offloadInfo.has_video);
2350
2351 // Check if offload has been disabled
2352 char propValue[PROPERTY_VALUE_MAX];
2353 if (property_get("audio.offload.disable", propValue, "0")) {
2354 if (atoi(propValue) != 0) {
2355 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2356 return false;
2357 }
2358 }
2359
2360 // Check if stream type is music, then only allow offload as of now.
2361 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2362 {
2363 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2364 return false;
2365 }
2366
2367 //TODO: enable audio offloading with video when ready
2368 if (offloadInfo.has_video)
2369 {
2370 ALOGV("isOffloadSupported: has_video == true, returning false");
2371 return false;
2372 }
2373
2374 //If duration is less than minimum value defined in property, return false
2375 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2376 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2377 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2378 return false;
2379 }
2380 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2381 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2382 return false;
2383 }
2384
2385 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2386 // creating an offloaded track and tearing it down immediately after start when audioflinger
2387 // detects there is an active non offloadable effect.
2388 // FIXME: We should check the audio session here but we do not have it in this context.
2389 // This may prevent offloading in rare situations where effects are left active by apps
2390 // in the background.
2391 if (isNonOffloadableEffectEnabled()) {
2392 return false;
2393 }
2394
2395 // See if there is a profile to support this.
2396 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002397 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002398 offloadInfo.sample_rate,
2399 offloadInfo.format,
2400 offloadInfo.channel_mask,
2401 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002402 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2403 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002404}
2405
Eric Laurent6a94d692014-05-20 11:18:06 -07002406status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2407 audio_port_type_t type,
2408 unsigned int *num_ports,
2409 struct audio_port *ports,
2410 unsigned int *generation)
2411{
2412 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2413 generation == NULL) {
2414 return BAD_VALUE;
2415 }
2416 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2417 if (ports == NULL) {
2418 *num_ports = 0;
2419 }
2420
2421 size_t portsWritten = 0;
2422 size_t portsMax = *num_ports;
2423 *num_ports = 0;
2424 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2425 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2426 for (size_t i = 0;
2427 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2428 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2429 }
2430 *num_ports += mAvailableOutputDevices.size();
2431 }
2432 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2433 for (size_t i = 0;
2434 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2435 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2436 }
2437 *num_ports += mAvailableInputDevices.size();
2438 }
2439 }
2440 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2441 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2442 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2443 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2444 }
2445 *num_ports += mInputs.size();
2446 }
2447 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002448 size_t numOutputs = 0;
2449 for (size_t i = 0; i < mOutputs.size(); i++) {
2450 if (!mOutputs[i]->isDuplicated()) {
2451 numOutputs++;
2452 if (portsWritten < portsMax) {
2453 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2454 }
2455 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002456 }
Eric Laurent84c70242014-06-23 08:46:27 -07002457 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002458 }
2459 }
2460 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002461 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002462 return NO_ERROR;
2463}
2464
2465status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2466{
2467 return NO_ERROR;
2468}
2469
Eric Laurent1f2f2232014-06-02 12:01:23 -07002470sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002471 audio_port_handle_t id) const
2472{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002473 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002474 for (size_t i = 0; i < mOutputs.size(); i++) {
2475 outputDesc = mOutputs.valueAt(i);
2476 if (outputDesc->mId == id) {
2477 break;
2478 }
2479 }
2480 return outputDesc;
2481}
2482
Eric Laurent1f2f2232014-06-02 12:01:23 -07002483sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002484 audio_port_handle_t id) const
2485{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002486 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002487 for (size_t i = 0; i < mInputs.size(); i++) {
2488 inputDesc = mInputs.valueAt(i);
2489 if (inputDesc->mId == id) {
2490 break;
2491 }
2492 }
2493 return inputDesc;
2494}
2495
Eric Laurent1f2f2232014-06-02 12:01:23 -07002496sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2497 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002498{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002499 sp <HwModule> module;
2500
Eric Laurent6a94d692014-05-20 11:18:06 -07002501 for (size_t i = 0; i < mHwModules.size(); i++) {
2502 if (mHwModules[i]->mHandle == 0) {
2503 continue;
2504 }
2505 if (audio_is_output_device(device)) {
2506 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2507 {
2508 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2509 return mHwModules[i];
2510 }
2511 }
2512 } else {
2513 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2514 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2515 device & ~AUDIO_DEVICE_BIT_IN) {
2516 return mHwModules[i];
2517 }
2518 }
2519 }
2520 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002521 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002522}
2523
Eric Laurent1f2f2232014-06-02 12:01:23 -07002524sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002525{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002526 sp <HwModule> module;
2527
Eric Laurent1afeecb2014-05-14 08:52:28 -07002528 for (size_t i = 0; i < mHwModules.size(); i++)
2529 {
2530 if (strcmp(mHwModules[i]->mName, name) == 0) {
2531 return mHwModules[i];
2532 }
2533 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002534 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002535}
2536
Eric Laurentc2730ba2014-07-20 15:47:07 -07002537audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2538{
2539 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2540 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2541 return devices & mAvailableOutputDevices.types();
2542}
2543
2544audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2545{
2546 audio_module_handle_t primaryHandle =
2547 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2548 audio_devices_t devices = AUDIO_DEVICE_NONE;
2549 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2550 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2551 devices |= mAvailableInputDevices[i]->mDeviceType;
2552 }
2553 }
2554 return devices;
2555}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002556
Eric Laurent6a94d692014-05-20 11:18:06 -07002557status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2558 audio_patch_handle_t *handle,
2559 uid_t uid)
2560{
2561 ALOGV("createAudioPatch()");
2562
2563 if (handle == NULL || patch == NULL) {
2564 return BAD_VALUE;
2565 }
2566 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2567
Eric Laurent874c42872014-08-08 15:13:39 -07002568 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2569 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2570 return BAD_VALUE;
2571 }
2572 // only one source per audio patch supported for now
2573 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002574 return INVALID_OPERATION;
2575 }
Eric Laurent874c42872014-08-08 15:13:39 -07002576
2577 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002578 return INVALID_OPERATION;
2579 }
Eric Laurent874c42872014-08-08 15:13:39 -07002580 for (size_t i = 0; i < patch->num_sinks; i++) {
2581 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2582 return INVALID_OPERATION;
2583 }
2584 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002585
2586 sp<AudioPatch> patchDesc;
2587 ssize_t index = mAudioPatches.indexOfKey(*handle);
2588
Eric Laurent6a94d692014-05-20 11:18:06 -07002589 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2590 patch->sources[0].role,
2591 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002592#if LOG_NDEBUG == 0
2593 for (size_t i = 0; i < patch->num_sinks; i++) {
2594 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2595 patch->sinks[i].role,
2596 patch->sinks[i].type);
2597 }
2598#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002599
2600 if (index >= 0) {
2601 patchDesc = mAudioPatches.valueAt(index);
2602 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2603 mUidCached, patchDesc->mUid, uid);
2604 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2605 return INVALID_OPERATION;
2606 }
2607 } else {
2608 *handle = 0;
2609 }
2610
2611 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002612 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002613 if (outputDesc == NULL) {
2614 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2615 return BAD_VALUE;
2616 }
Eric Laurent84c70242014-06-23 08:46:27 -07002617 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2618 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002619 if (patchDesc != 0) {
2620 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2621 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2622 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2623 return BAD_VALUE;
2624 }
2625 }
Eric Laurent874c42872014-08-08 15:13:39 -07002626 DeviceVector devices;
2627 for (size_t i = 0; i < patch->num_sinks; i++) {
2628 // Only support mix to devices connection
2629 // TODO add support for mix to mix connection
2630 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2631 ALOGV("createAudioPatch() source mix but sink is not a device");
2632 return INVALID_OPERATION;
2633 }
2634 sp<DeviceDescriptor> devDesc =
2635 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2636 if (devDesc == 0) {
2637 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2638 return BAD_VALUE;
2639 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002640
Eric Laurent874c42872014-08-08 15:13:39 -07002641 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002642 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002643 patch->sources[0].sample_rate,
2644 NULL, // updatedSamplingRate
2645 patch->sources[0].format,
2646 patch->sources[0].channel_mask,
2647 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2648 ALOGV("createAudioPatch() profile not supported for device %08x",
2649 devDesc->mDeviceType);
2650 return INVALID_OPERATION;
2651 }
2652 devices.add(devDesc);
2653 }
2654 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002655 return INVALID_OPERATION;
2656 }
Eric Laurent874c42872014-08-08 15:13:39 -07002657
Eric Laurent6a94d692014-05-20 11:18:06 -07002658 // TODO: reconfigure output format and channels here
2659 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002660 devices.types(), outputDesc->mIoHandle);
2661 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002662 index = mAudioPatches.indexOfKey(*handle);
2663 if (index >= 0) {
2664 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2665 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2666 }
2667 patchDesc = mAudioPatches.valueAt(index);
2668 patchDesc->mUid = uid;
2669 ALOGV("createAudioPatch() success");
2670 } else {
2671 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2672 return INVALID_OPERATION;
2673 }
2674 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2675 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2676 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002677 // only one sink supported when connecting an input device to a mix
2678 if (patch->num_sinks > 1) {
2679 return INVALID_OPERATION;
2680 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002681 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002682 if (inputDesc == NULL) {
2683 return BAD_VALUE;
2684 }
2685 if (patchDesc != 0) {
2686 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2687 return BAD_VALUE;
2688 }
2689 }
2690 sp<DeviceDescriptor> devDesc =
2691 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2692 if (devDesc == 0) {
2693 return BAD_VALUE;
2694 }
2695
Eric Laurent84c70242014-06-23 08:46:27 -07002696 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002697 devDesc->mAddress,
2698 patch->sinks[0].sample_rate,
2699 NULL, /*updatedSampleRate*/
2700 patch->sinks[0].format,
2701 patch->sinks[0].channel_mask,
2702 // FIXME for the parameter type,
2703 // and the NONE
2704 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002705 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002706 return INVALID_OPERATION;
2707 }
2708 // TODO: reconfigure output format and channels here
2709 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002710 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002711 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002712 index = mAudioPatches.indexOfKey(*handle);
2713 if (index >= 0) {
2714 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2715 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2716 }
2717 patchDesc = mAudioPatches.valueAt(index);
2718 patchDesc->mUid = uid;
2719 ALOGV("createAudioPatch() success");
2720 } else {
2721 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2722 return INVALID_OPERATION;
2723 }
2724 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2725 // device to device connection
2726 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002727 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002728 return BAD_VALUE;
2729 }
2730 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002731 sp<DeviceDescriptor> srcDeviceDesc =
2732 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002733 if (srcDeviceDesc == 0) {
2734 return BAD_VALUE;
2735 }
Eric Laurent874c42872014-08-08 15:13:39 -07002736
Eric Laurent6a94d692014-05-20 11:18:06 -07002737 //update source and sink with our own data as the data passed in the patch may
2738 // be incomplete.
2739 struct audio_patch newPatch = *patch;
2740 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002741
Eric Laurent874c42872014-08-08 15:13:39 -07002742 for (size_t i = 0; i < patch->num_sinks; i++) {
2743 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2744 ALOGV("createAudioPatch() source device but one sink is not a device");
2745 return INVALID_OPERATION;
2746 }
2747
2748 sp<DeviceDescriptor> sinkDeviceDesc =
2749 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2750 if (sinkDeviceDesc == 0) {
2751 return BAD_VALUE;
2752 }
2753 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2754
2755 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2756 // only one sink supported when connected devices across HW modules
2757 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002758 return INVALID_OPERATION;
2759 }
Eric Laurent874c42872014-08-08 15:13:39 -07002760 SortedVector<audio_io_handle_t> outputs =
2761 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2762 mOutputs);
2763 // if the sink device is reachable via an opened output stream, request to go via
2764 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002765 audio_io_handle_t output = selectOutput(outputs,
2766 AUDIO_OUTPUT_FLAG_NONE,
2767 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002768 if (output != AUDIO_IO_HANDLE_NONE) {
2769 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2770 if (outputDesc->isDuplicated()) {
2771 return INVALID_OPERATION;
2772 }
2773 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2774 newPatch.num_sources = 2;
2775 }
Eric Laurent83b88082014-06-20 18:31:16 -07002776 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002777 }
2778 // TODO: check from routing capabilities in config file and other conflicting patches
2779
2780 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2781 if (index >= 0) {
2782 afPatchHandle = patchDesc->mAfPatchHandle;
2783 }
2784
2785 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2786 &afPatchHandle,
2787 0);
2788 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2789 status, afPatchHandle);
2790 if (status == NO_ERROR) {
2791 if (index < 0) {
2792 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2793 &newPatch, uid);
2794 addAudioPatch(patchDesc->mHandle, patchDesc);
2795 } else {
2796 patchDesc->mPatch = newPatch;
2797 }
2798 patchDesc->mAfPatchHandle = afPatchHandle;
2799 *handle = patchDesc->mHandle;
2800 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002801 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002802 } else {
2803 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2804 status);
2805 return INVALID_OPERATION;
2806 }
2807 } else {
2808 return BAD_VALUE;
2809 }
2810 } else {
2811 return BAD_VALUE;
2812 }
2813 return NO_ERROR;
2814}
2815
2816status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2817 uid_t uid)
2818{
2819 ALOGV("releaseAudioPatch() patch %d", handle);
2820
2821 ssize_t index = mAudioPatches.indexOfKey(handle);
2822
2823 if (index < 0) {
2824 return BAD_VALUE;
2825 }
2826 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2827 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2828 mUidCached, patchDesc->mUid, uid);
2829 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2830 return INVALID_OPERATION;
2831 }
2832
2833 struct audio_patch *patch = &patchDesc->mPatch;
2834 patchDesc->mUid = mUidCached;
2835 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002836 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002837 if (outputDesc == NULL) {
2838 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2839 return BAD_VALUE;
2840 }
2841
2842 setOutputDevice(outputDesc->mIoHandle,
2843 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2844 true,
2845 0,
2846 NULL);
2847 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2848 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002849 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002850 if (inputDesc == NULL) {
2851 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2852 return BAD_VALUE;
2853 }
2854 setInputDevice(inputDesc->mIoHandle,
2855 getNewInputDevice(inputDesc->mIoHandle),
2856 true,
2857 NULL);
2858 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2859 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2860 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2861 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2862 status, patchDesc->mAfPatchHandle);
2863 removeAudioPatch(patchDesc->mHandle);
2864 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002865 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002866 } else {
2867 return BAD_VALUE;
2868 }
2869 } else {
2870 return BAD_VALUE;
2871 }
2872 return NO_ERROR;
2873}
2874
2875status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2876 struct audio_patch *patches,
2877 unsigned int *generation)
2878{
2879 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2880 generation == NULL) {
2881 return BAD_VALUE;
2882 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002883 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002884 *num_patches, patches, mAudioPatches.size());
2885 if (patches == NULL) {
2886 *num_patches = 0;
2887 }
2888
2889 size_t patchesWritten = 0;
2890 size_t patchesMax = *num_patches;
2891 for (size_t i = 0;
2892 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2893 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2894 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002895 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002896 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2897 }
2898 *num_patches = mAudioPatches.size();
2899
2900 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002901 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002902 return NO_ERROR;
2903}
2904
Eric Laurente1715a42014-05-20 11:30:42 -07002905status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002906{
Eric Laurente1715a42014-05-20 11:30:42 -07002907 ALOGV("setAudioPortConfig()");
2908
2909 if (config == NULL) {
2910 return BAD_VALUE;
2911 }
2912 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2913 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002914 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2915 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002916 }
2917
Eric Laurenta121f902014-06-03 13:32:54 -07002918 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002919 if (config->type == AUDIO_PORT_TYPE_MIX) {
2920 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002921 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002922 if (outputDesc == NULL) {
2923 return BAD_VALUE;
2924 }
Eric Laurent84c70242014-06-23 08:46:27 -07002925 ALOG_ASSERT(!outputDesc->isDuplicated(),
2926 "setAudioPortConfig() called on duplicated output %d",
2927 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002928 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002929 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002930 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002931 if (inputDesc == NULL) {
2932 return BAD_VALUE;
2933 }
Eric Laurenta121f902014-06-03 13:32:54 -07002934 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002935 } else {
2936 return BAD_VALUE;
2937 }
2938 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2939 sp<DeviceDescriptor> deviceDesc;
2940 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2941 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2942 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2943 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2944 } else {
2945 return BAD_VALUE;
2946 }
2947 if (deviceDesc == NULL) {
2948 return BAD_VALUE;
2949 }
Eric Laurenta121f902014-06-03 13:32:54 -07002950 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002951 } else {
2952 return BAD_VALUE;
2953 }
2954
Eric Laurenta121f902014-06-03 13:32:54 -07002955 struct audio_port_config backupConfig;
2956 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2957 if (status == NO_ERROR) {
2958 struct audio_port_config newConfig;
2959 audioPortConfig->toAudioPortConfig(&newConfig, config);
2960 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002961 }
Eric Laurenta121f902014-06-03 13:32:54 -07002962 if (status != NO_ERROR) {
2963 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002964 }
Eric Laurente1715a42014-05-20 11:30:42 -07002965
2966 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002967}
2968
2969void AudioPolicyManager::clearAudioPatches(uid_t uid)
2970{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002971 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002972 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2973 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002974 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002975 }
2976 }
2977}
2978
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002979status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2980 audio_io_handle_t *ioHandle,
2981 audio_devices_t *device)
2982{
2983 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2984 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002985 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002986
2987 mSoundTriggerSessions.add(*session, *ioHandle);
2988
2989 return NO_ERROR;
2990}
2991
2992status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2993{
2994 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2995 if (index < 0) {
2996 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2997 return BAD_VALUE;
2998 }
2999
3000 mSoundTriggerSessions.removeItem(session);
3001 return NO_ERROR;
3002}
3003
Eric Laurent6a94d692014-05-20 11:18:06 -07003004status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
3005 const sp<AudioPatch>& patch)
3006{
3007 ssize_t index = mAudioPatches.indexOfKey(handle);
3008
3009 if (index >= 0) {
3010 ALOGW("addAudioPatch() patch %d already in", handle);
3011 return ALREADY_EXISTS;
3012 }
3013 mAudioPatches.add(handle, patch);
3014 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
3015 "sink handle %d",
3016 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
3017 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
3018 return NO_ERROR;
3019}
3020
3021status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
3022{
3023 ssize_t index = mAudioPatches.indexOfKey(handle);
3024
3025 if (index < 0) {
3026 ALOGW("removeAudioPatch() patch %d not in", handle);
3027 return ALREADY_EXISTS;
3028 }
3029 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
3030 mAudioPatches.valueAt(index)->mAfPatchHandle);
3031 mAudioPatches.removeItemsAt(index);
3032 return NO_ERROR;
3033}
3034
Eric Laurente552edb2014-03-10 17:42:56 -07003035// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003036// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003037// ----------------------------------------------------------------------------
3038
Eric Laurent3a4311c2014-03-17 12:00:47 -07003039uint32_t AudioPolicyManager::nextUniqueId()
3040{
3041 return android_atomic_inc(&mNextUniqueId);
3042}
3043
Eric Laurent6a94d692014-05-20 11:18:06 -07003044uint32_t AudioPolicyManager::nextAudioPortGeneration()
3045{
3046 return android_atomic_inc(&mAudioPortGeneration);
3047}
3048
Paul McLeane743a472015-01-28 11:07:31 -08003049int32_t volatile AudioPolicyManager::mNextUniqueId = 1;
3050
Eric Laurente0720872014-03-11 09:30:41 -07003051AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003052 :
3053#ifdef AUDIO_POLICY_TEST
3054 Thread(false),
3055#endif //AUDIO_POLICY_TEST
3056 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07003057 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07003058 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
3059 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003060 mA2dpSuspended(false),
Paul McLeane743a472015-01-28 11:07:31 -08003061 mSpeakerDrcEnabled(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003062 mAudioPortGeneration(1),
3063 mBeaconMuteRefCount(0),
3064 mBeaconPlayingRefCount(0),
3065 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003066{
Eric Laurent6a94d692014-05-20 11:18:06 -07003067 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07003068 mpClientInterface = clientInterface;
3069
Eric Laurent3b73df72014-03-11 09:06:29 -07003070 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
3071 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003072 }
3073
Paul McLeane743a472015-01-28 11:07:31 -08003074 mDefaultOutputDevice = new DeviceDescriptor(String8("Speaker"), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07003075 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
3076 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
3077 ALOGE("could not load audio policy configuration file, setting defaults");
3078 defaultAudioPolicyConfig();
3079 }
3080 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003081 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003082
3083 // must be done after reading the policy
3084 initializeVolumeCurves();
3085
3086 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003087 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3088 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003089 for (size_t i = 0; i < mHwModules.size(); i++) {
3090 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
3091 if (mHwModules[i]->mHandle == 0) {
3092 ALOGW("could not open HW module %s", mHwModules[i]->mName);
3093 continue;
3094 }
3095 // open all output streams needed to access attached devices
3096 // except for direct output streams that are only opened when they are actually
3097 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003098 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003099 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3100 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003101 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003102
Eric Laurent3a4311c2014-03-17 12:00:47 -07003103 if (outProfile->mSupportedDevices.isEmpty()) {
3104 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
3105 continue;
3106 }
3107
Eric Laurentd78f1532014-09-16 16:38:20 -07003108 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
3109 continue;
3110 }
Eric Laurent83b88082014-06-20 18:31:16 -07003111 audio_devices_t profileType = outProfile->mSupportedDevices.types();
3112 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
3113 profileType = mDefaultOutputDevice->mDeviceType;
3114 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07003115 // chose first device present in mSupportedDevices also part of
3116 // outputDeviceTypes
3117 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3118 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
3119 if ((profileType & outputDeviceTypes) != 0) {
3120 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003121 }
Eric Laurente552edb2014-03-10 17:42:56 -07003122 }
3123 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003124 if ((profileType & outputDeviceTypes) == 0) {
3125 continue;
3126 }
3127 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
3128
3129 outputDesc->mDevice = profileType;
3130 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3131 config.sample_rate = outputDesc->mSamplingRate;
3132 config.channel_mask = outputDesc->mChannelMask;
3133 config.format = outputDesc->mFormat;
3134 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3135 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
3136 &output,
3137 &config,
3138 &outputDesc->mDevice,
3139 String8(""),
3140 &outputDesc->mLatency,
3141 outputDesc->mFlags);
3142
3143 if (status != NO_ERROR) {
3144 ALOGW("Cannot open output stream for device %08x on hw module %s",
3145 outputDesc->mDevice,
3146 mHwModules[i]->mName);
3147 } else {
3148 outputDesc->mSamplingRate = config.sample_rate;
3149 outputDesc->mChannelMask = config.channel_mask;
3150 outputDesc->mFormat = config.format;
3151
3152 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3153 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
3154 ssize_t index =
3155 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
3156 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003157 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3158 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003159 }
3160 }
3161 if (mPrimaryOutput == 0 &&
3162 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
3163 mPrimaryOutput = output;
3164 }
3165 addOutput(output, outputDesc);
3166 setOutputDevice(output,
3167 outputDesc->mDevice,
3168 true);
3169 }
Eric Laurente552edb2014-03-10 17:42:56 -07003170 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003171 // open input streams needed to access attached devices to validate
3172 // mAvailableInputDevices list
3173 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3174 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003175 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003176
Eric Laurent3a4311c2014-03-17 12:00:47 -07003177 if (inProfile->mSupportedDevices.isEmpty()) {
3178 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
3179 continue;
3180 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003181 // chose first device present in mSupportedDevices also part of
3182 // inputDeviceTypes
3183 audio_devices_t profileType = AUDIO_DEVICE_NONE;
3184 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3185 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
3186 if (profileType & inputDeviceTypes) {
3187 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003188 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003189 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003190 if ((profileType & inputDeviceTypes) == 0) {
3191 continue;
3192 }
3193 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
3194
3195 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
3196 inputDesc->mDevice = profileType;
3197
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003198 // find the address
3199 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3200 // the inputs vector must be of size 1, but we don't want to crash here
3201 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3202 : String8("");
3203 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3204 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3205
Eric Laurentd78f1532014-09-16 16:38:20 -07003206 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3207 config.sample_rate = inputDesc->mSamplingRate;
3208 config.channel_mask = inputDesc->mChannelMask;
3209 config.format = inputDesc->mFormat;
3210 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3211 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
3212 &input,
3213 &config,
3214 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003215 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003216 AUDIO_SOURCE_MIC,
3217 AUDIO_INPUT_FLAG_NONE);
3218
3219 if (status == NO_ERROR) {
3220 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3221 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
3222 ssize_t index =
3223 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
3224 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003225 if (index >= 0 && !mAvailableInputDevices[index]->isAttached()) {
3226 mAvailableInputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003227 }
3228 }
3229 mpClientInterface->closeInput(input);
3230 } else {
3231 ALOGW("Cannot open input stream for device %08x on hw module %s",
3232 inputDesc->mDevice,
3233 mHwModules[i]->mName);
3234 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003235 }
3236 }
3237 // make sure all attached devices have been allocated a unique ID
3238 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003239 if (!mAvailableOutputDevices[i]->isAttached()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003240 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003241 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3242 continue;
3243 }
3244 i++;
3245 }
3246 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003247 if (!mAvailableInputDevices[i]->isAttached()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003248 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003249 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3250 continue;
3251 }
3252 i++;
3253 }
3254 // make sure default device is reachable
3255 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003256 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003257 }
Eric Laurente552edb2014-03-10 17:42:56 -07003258
3259 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3260
3261 updateDevicesAndOutputs();
3262
3263#ifdef AUDIO_POLICY_TEST
3264 if (mPrimaryOutput != 0) {
3265 AudioParameter outputCmd = AudioParameter();
3266 outputCmd.addInt(String8("set_id"), 0);
3267 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3268
3269 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3270 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003271 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3272 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003273 mTestLatencyMs = 0;
3274 mCurOutput = 0;
3275 mDirectOutput = false;
3276 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3277 mTestOutputs[i] = 0;
3278 }
3279
3280 const size_t SIZE = 256;
3281 char buffer[SIZE];
3282 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3283 run(buffer, ANDROID_PRIORITY_AUDIO);
3284 }
3285#endif //AUDIO_POLICY_TEST
3286}
3287
Eric Laurente0720872014-03-11 09:30:41 -07003288AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003289{
3290#ifdef AUDIO_POLICY_TEST
3291 exit();
3292#endif //AUDIO_POLICY_TEST
3293 for (size_t i = 0; i < mOutputs.size(); i++) {
3294 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003295 }
3296 for (size_t i = 0; i < mInputs.size(); i++) {
3297 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003298 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003299 mAvailableOutputDevices.clear();
3300 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003301 mOutputs.clear();
3302 mInputs.clear();
3303 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003304}
3305
Eric Laurente0720872014-03-11 09:30:41 -07003306status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003307{
3308 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
3309}
3310
3311#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003312bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003313{
3314 ALOGV("entering threadLoop()");
3315 while (!exitPending())
3316 {
3317 String8 command;
3318 int valueInt;
3319 String8 value;
3320
3321 Mutex::Autolock _l(mLock);
3322 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3323
3324 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3325 AudioParameter param = AudioParameter(command);
3326
3327 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3328 valueInt != 0) {
3329 ALOGV("Test command %s received", command.string());
3330 String8 target;
3331 if (param.get(String8("target"), target) != NO_ERROR) {
3332 target = "Manager";
3333 }
3334 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3335 param.remove(String8("test_cmd_policy_output"));
3336 mCurOutput = valueInt;
3337 }
3338 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3339 param.remove(String8("test_cmd_policy_direct"));
3340 if (value == "false") {
3341 mDirectOutput = false;
3342 } else if (value == "true") {
3343 mDirectOutput = true;
3344 }
3345 }
3346 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3347 param.remove(String8("test_cmd_policy_input"));
3348 mTestInput = valueInt;
3349 }
3350
3351 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3352 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003353 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003354 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003355 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003356 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003357 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003358 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003359 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003360 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003361 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003362 if (target == "Manager") {
3363 mTestFormat = format;
3364 } else if (mTestOutputs[mCurOutput] != 0) {
3365 AudioParameter outputParam = AudioParameter();
3366 outputParam.addInt(String8("format"), format);
3367 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3368 }
3369 }
3370 }
3371 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3372 param.remove(String8("test_cmd_policy_channels"));
3373 int channels = 0;
3374
3375 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003376 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003377 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003378 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003379 }
3380 if (channels != 0) {
3381 if (target == "Manager") {
3382 mTestChannels = channels;
3383 } else if (mTestOutputs[mCurOutput] != 0) {
3384 AudioParameter outputParam = AudioParameter();
3385 outputParam.addInt(String8("channels"), channels);
3386 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3387 }
3388 }
3389 }
3390 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3391 param.remove(String8("test_cmd_policy_sampleRate"));
3392 if (valueInt >= 0 && valueInt <= 96000) {
3393 int samplingRate = valueInt;
3394 if (target == "Manager") {
3395 mTestSamplingRate = samplingRate;
3396 } else if (mTestOutputs[mCurOutput] != 0) {
3397 AudioParameter outputParam = AudioParameter();
3398 outputParam.addInt(String8("sampling_rate"), samplingRate);
3399 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3400 }
3401 }
3402 }
3403
3404 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3405 param.remove(String8("test_cmd_policy_reopen"));
3406
Eric Laurent1f2f2232014-06-02 12:01:23 -07003407 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003408 mpClientInterface->closeOutput(mPrimaryOutput);
3409
3410 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3411
Eric Laurente552edb2014-03-10 17:42:56 -07003412 mOutputs.removeItem(mPrimaryOutput);
3413
Eric Laurent1f2f2232014-06-02 12:01:23 -07003414 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003415 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003416 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3417 config.sample_rate = outputDesc->mSamplingRate;
3418 config.channel_mask = outputDesc->mChannelMask;
3419 config.format = outputDesc->mFormat;
3420 status_t status = mpClientInterface->openOutput(moduleHandle,
3421 &mPrimaryOutput,
3422 &config,
3423 &outputDesc->mDevice,
3424 String8(""),
3425 &outputDesc->mLatency,
3426 outputDesc->mFlags);
3427 if (status != NO_ERROR) {
3428 ALOGE("Failed to reopen hardware output stream, "
3429 "samplingRate: %d, format %d, channels %d",
3430 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003431 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003432 outputDesc->mSamplingRate = config.sample_rate;
3433 outputDesc->mChannelMask = config.channel_mask;
3434 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003435 AudioParameter outputCmd = AudioParameter();
3436 outputCmd.addInt(String8("set_id"), 0);
3437 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3438 addOutput(mPrimaryOutput, outputDesc);
3439 }
3440 }
3441
3442
3443 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3444 }
3445 }
3446 return false;
3447}
3448
Eric Laurente0720872014-03-11 09:30:41 -07003449void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003450{
3451 {
3452 AutoMutex _l(mLock);
3453 requestExit();
3454 mWaitWorkCV.signal();
3455 }
3456 requestExitAndWait();
3457}
3458
Eric Laurente0720872014-03-11 09:30:41 -07003459int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003460{
3461 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3462 if (output == mTestOutputs[i]) return i;
3463 }
3464 return 0;
3465}
3466#endif //AUDIO_POLICY_TEST
3467
3468// ---
3469
Eric Laurent1f2f2232014-06-02 12:01:23 -07003470void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003471{
Eric Laurent1c333e22014-05-20 10:48:17 -07003472 outputDesc->mIoHandle = output;
3473 outputDesc->mId = nextUniqueId();
3474 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003475 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003476}
3477
Eric Laurent1f2f2232014-06-02 12:01:23 -07003478void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003479{
Eric Laurent1c333e22014-05-20 10:48:17 -07003480 inputDesc->mIoHandle = input;
3481 inputDesc->mId = nextUniqueId();
3482 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003483 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003484}
Eric Laurente552edb2014-03-10 17:42:56 -07003485
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003486void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003487 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003488 const String8 address /*in*/,
3489 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003490 sp<DeviceDescriptor> devDesc =
3491 desc->mProfile->mSupportedDevices.getDevice(device, address);
3492 if (devDesc != 0) {
3493 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3494 desc->mIoHandle, address.string());
3495 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003496 }
3497}
3498
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003499status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003500 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003501 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003502 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003503{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003504 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003505 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003506 // erase all current sample rates, formats and channel masks
3507 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003508
Eric Laurent3b73df72014-03-11 09:06:29 -07003509 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003510 // first list already open outputs that can be routed to this device
3511 for (size_t i = 0; i < mOutputs.size(); i++) {
3512 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003513 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003514 if (!deviceDistinguishesOnAddress(device)) {
3515 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3516 outputs.add(mOutputs.keyAt(i));
3517 } else {
3518 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003519 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003520 }
Eric Laurente552edb2014-03-10 17:42:56 -07003521 }
3522 }
3523 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003524 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003525 for (size_t i = 0; i < mHwModules.size(); i++)
3526 {
3527 if (mHwModules[i]->mHandle == 0) {
3528 continue;
3529 }
3530 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3531 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003532 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3533 if (profile->mSupportedDevices.types() & device) {
3534 if (!deviceDistinguishesOnAddress(device) ||
3535 address == profile->mSupportedDevices[0]->mAddress) {
3536 profiles.add(profile);
3537 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3538 }
Eric Laurente552edb2014-03-10 17:42:56 -07003539 }
3540 }
3541 }
3542
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003543 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3544
Eric Laurente552edb2014-03-10 17:42:56 -07003545 if (profiles.isEmpty() && outputs.isEmpty()) {
3546 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3547 return BAD_VALUE;
3548 }
3549
3550 // open outputs for matching profiles if needed. Direct outputs are also opened to
3551 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3552 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003553 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003554
3555 // nothing to do if one output is already opened for this profile
3556 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003557 for (j = 0; j < outputs.size(); j++) {
3558 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003559 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003560 // matching profile: save the sample rates, format and channel masks supported
3561 // by the profile in our device descriptor
3562 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003563 break;
3564 }
3565 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003566 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003567 continue;
3568 }
3569
Eric Laurent83b88082014-06-20 18:31:16 -07003570 ALOGV("opening output for device %08x with params %s profile %p",
3571 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003572 desc = new AudioOutputDescriptor(profile);
3573 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003574 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3575 config.sample_rate = desc->mSamplingRate;
3576 config.channel_mask = desc->mChannelMask;
3577 config.format = desc->mFormat;
3578 config.offload_info.sample_rate = desc->mSamplingRate;
3579 config.offload_info.channel_mask = desc->mChannelMask;
3580 config.offload_info.format = desc->mFormat;
3581 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3582 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3583 &output,
3584 &config,
3585 &desc->mDevice,
3586 address,
3587 &desc->mLatency,
3588 desc->mFlags);
3589 if (status == NO_ERROR) {
3590 desc->mSamplingRate = config.sample_rate;
3591 desc->mChannelMask = config.channel_mask;
3592 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003593
Eric Laurentd4692962014-05-05 18:13:44 -07003594 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003595 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003596 char *param = audio_device_address_to_parameter(device, address);
3597 mpClientInterface->setParameters(output, String8(param));
3598 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003599 }
3600
Eric Laurentd4692962014-05-05 18:13:44 -07003601 // Here is where we step through and resolve any "dynamic" fields
3602 String8 reply;
3603 char *value;
3604 if (profile->mSamplingRates[0] == 0) {
3605 reply = mpClientInterface->getParameters(output,
3606 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003607 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003608 reply.string());
3609 value = strpbrk((char *)reply.string(), "=");
3610 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003611 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003612 }
Eric Laurentd4692962014-05-05 18:13:44 -07003613 }
3614 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3615 reply = mpClientInterface->getParameters(output,
3616 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003617 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003618 reply.string());
3619 value = strpbrk((char *)reply.string(), "=");
3620 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003621 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003622 }
Eric Laurentd4692962014-05-05 18:13:44 -07003623 }
3624 if (profile->mChannelMasks[0] == 0) {
3625 reply = mpClientInterface->getParameters(output,
3626 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003627 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003628 reply.string());
3629 value = strpbrk((char *)reply.string(), "=");
3630 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003631 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003632 }
Eric Laurentd4692962014-05-05 18:13:44 -07003633 }
3634 if (((profile->mSamplingRates[0] == 0) &&
3635 (profile->mSamplingRates.size() < 2)) ||
3636 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3637 (profile->mFormats.size() < 2)) ||
3638 ((profile->mChannelMasks[0] == 0) &&
3639 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003640 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003641 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003642 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003643 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3644 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003645 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003646 config.sample_rate = profile->pickSamplingRate();
3647 config.channel_mask = profile->pickChannelMask();
3648 config.format = profile->pickFormat();
3649 config.offload_info.sample_rate = config.sample_rate;
3650 config.offload_info.channel_mask = config.channel_mask;
3651 config.offload_info.format = config.format;
3652 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3653 &output,
3654 &config,
3655 &desc->mDevice,
3656 address,
3657 &desc->mLatency,
3658 desc->mFlags);
3659 if (status == NO_ERROR) {
3660 desc->mSamplingRate = config.sample_rate;
3661 desc->mChannelMask = config.channel_mask;
3662 desc->mFormat = config.format;
3663 } else {
3664 output = AUDIO_IO_HANDLE_NONE;
3665 }
Eric Laurentd4692962014-05-05 18:13:44 -07003666 }
3667
Eric Laurentcf2c0212014-07-25 16:20:43 -07003668 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003669 addOutput(output, desc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003670 if (deviceDistinguishesOnAddress(device) && address != "0") {
3671 ssize_t index = mPolicyMixes.indexOfKey(address);
3672 if (index >= 0) {
3673 mPolicyMixes[index]->mOutput = desc;
Eric Laurentc722f302014-12-10 11:21:49 -08003674 desc->mPolicyMix = &mPolicyMixes[index]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08003675 } else {
3676 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3677 address.string());
3678 }
Eric Laurentc722f302014-12-10 11:21:49 -08003679 } else if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
3680 // no duplicated output for direct outputs and
3681 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003682 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003683
Eric Laurentd4692962014-05-05 18:13:44 -07003684 // set initial stream volume for device
3685 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003686
Eric Laurentd4692962014-05-05 18:13:44 -07003687 //TODO: configure audio effect output stage here
3688
3689 // open a duplicating output thread for the new output and the primary output
3690 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3691 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003692 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003693 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003694 sp<AudioOutputDescriptor> dupOutputDesc =
3695 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003696 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3697 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3698 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3699 dupOutputDesc->mFormat = desc->mFormat;
3700 dupOutputDesc->mChannelMask = desc->mChannelMask;
3701 dupOutputDesc->mLatency = desc->mLatency;
3702 addOutput(duplicatedOutput, dupOutputDesc);
3703 applyStreamVolumes(duplicatedOutput, device, 0, true);
3704 } else {
3705 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3706 mPrimaryOutput, output);
3707 mpClientInterface->closeOutput(output);
3708 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003709 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003710 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003711 }
Eric Laurente552edb2014-03-10 17:42:56 -07003712 }
3713 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003714 } else {
3715 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003716 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003717 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003718 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003719 profiles.removeAt(profile_index);
3720 profile_index--;
3721 } else {
3722 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003723 devDesc->importAudioPort(profile);
3724
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003725 if (deviceDistinguishesOnAddress(device)) {
3726 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3727 device, address.string());
3728 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3729 NULL/*patch handle*/, address.string());
3730 }
Eric Laurente552edb2014-03-10 17:42:56 -07003731 ALOGV("checkOutputsForDevice(): adding output %d", output);
3732 }
3733 }
3734
3735 if (profiles.isEmpty()) {
3736 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3737 return BAD_VALUE;
3738 }
Eric Laurentd4692962014-05-05 18:13:44 -07003739 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003740 // check if one opened output is not needed any more after disconnecting one device
3741 for (size_t i = 0; i < mOutputs.size(); i++) {
3742 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003743 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003744 // exact match on device
3745 if (deviceDistinguishesOnAddress(device) &&
3746 (desc->mProfile->mSupportedDevices.types() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003747 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08003748 } else if (!(desc->mProfile->mSupportedDevices.types()
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003749 & mAvailableOutputDevices.types())) {
3750 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3751 mOutputs.keyAt(i));
3752 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003753 }
Eric Laurente552edb2014-03-10 17:42:56 -07003754 }
3755 }
Eric Laurentd4692962014-05-05 18:13:44 -07003756 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003757 for (size_t i = 0; i < mHwModules.size(); i++)
3758 {
3759 if (mHwModules[i]->mHandle == 0) {
3760 continue;
3761 }
3762 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3763 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003764 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003765 if (profile->mSupportedDevices.types() & device) {
3766 ALOGV("checkOutputsForDevice(): "
3767 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003768 if (profile->mSamplingRates[0] == 0) {
3769 profile->mSamplingRates.clear();
3770 profile->mSamplingRates.add(0);
3771 }
3772 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3773 profile->mFormats.clear();
3774 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3775 }
3776 if (profile->mChannelMasks[0] == 0) {
3777 profile->mChannelMasks.clear();
3778 profile->mChannelMasks.add(0);
3779 }
3780 }
3781 }
3782 }
3783 }
3784 return NO_ERROR;
3785}
3786
Eric Laurentd4692962014-05-05 18:13:44 -07003787status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3788 audio_policy_dev_state_t state,
3789 SortedVector<audio_io_handle_t>& inputs,
3790 const String8 address)
3791{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003792 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003793 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3794 // first list already open inputs that can be routed to this device
3795 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3796 desc = mInputs.valueAt(input_index);
3797 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3798 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3799 inputs.add(mInputs.keyAt(input_index));
3800 }
3801 }
3802
3803 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003804 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003805 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3806 {
3807 if (mHwModules[module_idx]->mHandle == 0) {
3808 continue;
3809 }
3810 for (size_t profile_index = 0;
3811 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3812 profile_index++)
3813 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003814 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3815
3816 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3817 if (!deviceDistinguishesOnAddress(device) ||
3818 address == profile->mSupportedDevices[0]->mAddress) {
3819 profiles.add(profile);
3820 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3821 profile_index, module_idx);
3822 }
Eric Laurentd4692962014-05-05 18:13:44 -07003823 }
3824 }
3825 }
3826
3827 if (profiles.isEmpty() && inputs.isEmpty()) {
3828 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3829 return BAD_VALUE;
3830 }
3831
3832 // open inputs for matching profiles if needed. Direct inputs are also opened to
3833 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3834 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3835
Eric Laurent1c333e22014-05-20 10:48:17 -07003836 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003837 // nothing to do if one input is already opened for this profile
3838 size_t input_index;
3839 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3840 desc = mInputs.valueAt(input_index);
3841 if (desc->mProfile == profile) {
3842 break;
3843 }
3844 }
3845 if (input_index != mInputs.size()) {
3846 continue;
3847 }
3848
3849 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3850 desc = new AudioInputDescriptor(profile);
3851 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003852 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3853 config.sample_rate = desc->mSamplingRate;
3854 config.channel_mask = desc->mChannelMask;
3855 config.format = desc->mFormat;
3856 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3857 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3858 &input,
3859 &config,
3860 &desc->mDevice,
3861 address,
3862 AUDIO_SOURCE_MIC,
3863 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003864
Eric Laurentcf2c0212014-07-25 16:20:43 -07003865 if (status == NO_ERROR) {
3866 desc->mSamplingRate = config.sample_rate;
3867 desc->mChannelMask = config.channel_mask;
3868 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003869
Eric Laurentd4692962014-05-05 18:13:44 -07003870 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003871 char *param = audio_device_address_to_parameter(device, address);
3872 mpClientInterface->setParameters(input, String8(param));
3873 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003874 }
3875
3876 // Here is where we step through and resolve any "dynamic" fields
3877 String8 reply;
3878 char *value;
3879 if (profile->mSamplingRates[0] == 0) {
3880 reply = mpClientInterface->getParameters(input,
3881 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3882 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3883 reply.string());
3884 value = strpbrk((char *)reply.string(), "=");
3885 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003886 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003887 }
3888 }
3889 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3890 reply = mpClientInterface->getParameters(input,
3891 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3892 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3893 value = strpbrk((char *)reply.string(), "=");
3894 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003895 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003896 }
3897 }
3898 if (profile->mChannelMasks[0] == 0) {
3899 reply = mpClientInterface->getParameters(input,
3900 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3901 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3902 reply.string());
3903 value = strpbrk((char *)reply.string(), "=");
3904 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003905 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003906 }
3907 }
3908 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3909 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3910 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3911 ALOGW("checkInputsForDevice() direct input missing param");
3912 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003913 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003914 }
3915
3916 if (input != 0) {
3917 addInput(input, desc);
3918 }
3919 } // endif input != 0
3920
Eric Laurentcf2c0212014-07-25 16:20:43 -07003921 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003922 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003923 profiles.removeAt(profile_index);
3924 profile_index--;
3925 } else {
3926 inputs.add(input);
3927 ALOGV("checkInputsForDevice(): adding input %d", input);
3928 }
3929 } // end scan profiles
3930
3931 if (profiles.isEmpty()) {
3932 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3933 return BAD_VALUE;
3934 }
3935 } else {
3936 // Disconnect
3937 // check if one opened input is not needed any more after disconnecting one device
3938 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3939 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003940 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3941 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003942 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3943 mInputs.keyAt(input_index));
3944 inputs.add(mInputs.keyAt(input_index));
3945 }
3946 }
3947 // Clear any profiles associated with the disconnected device.
3948 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3949 if (mHwModules[module_index]->mHandle == 0) {
3950 continue;
3951 }
3952 for (size_t profile_index = 0;
3953 profile_index < mHwModules[module_index]->mInputProfiles.size();
3954 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003955 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003956 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003957 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003958 profile_index, module_index);
3959 if (profile->mSamplingRates[0] == 0) {
3960 profile->mSamplingRates.clear();
3961 profile->mSamplingRates.add(0);
3962 }
3963 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3964 profile->mFormats.clear();
3965 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3966 }
3967 if (profile->mChannelMasks[0] == 0) {
3968 profile->mChannelMasks.clear();
3969 profile->mChannelMasks.add(0);
3970 }
3971 }
3972 }
3973 }
3974 } // end disconnect
3975
3976 return NO_ERROR;
3977}
3978
3979
Eric Laurente0720872014-03-11 09:30:41 -07003980void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003981{
3982 ALOGV("closeOutput(%d)", output);
3983
Eric Laurent1f2f2232014-06-02 12:01:23 -07003984 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003985 if (outputDesc == NULL) {
3986 ALOGW("closeOutput() unknown output %d", output);
3987 return;
3988 }
3989
Eric Laurent275e8e92014-11-30 15:14:47 -08003990 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
3991 if (mPolicyMixes[i]->mOutput == outputDesc) {
3992 mPolicyMixes[i]->mOutput.clear();
3993 }
3994 }
3995
Eric Laurente552edb2014-03-10 17:42:56 -07003996 // look for duplicated outputs connected to the output being removed.
3997 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003998 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003999 if (dupOutputDesc->isDuplicated() &&
4000 (dupOutputDesc->mOutput1 == outputDesc ||
4001 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004002 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004003 if (dupOutputDesc->mOutput1 == outputDesc) {
4004 outputDesc2 = dupOutputDesc->mOutput2;
4005 } else {
4006 outputDesc2 = dupOutputDesc->mOutput1;
4007 }
4008 // As all active tracks on duplicated output will be deleted,
4009 // and as they were also referenced on the other output, the reference
4010 // count for their stream type must be adjusted accordingly on
4011 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004012 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004013 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004014 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004015 }
4016 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4017 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4018
4019 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004020 mOutputs.removeItem(duplicatedOutput);
4021 }
4022 }
4023
Eric Laurent05b90f82014-08-27 15:32:29 -07004024 nextAudioPortGeneration();
4025
4026 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4027 if (index >= 0) {
4028 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4029 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4030 mAudioPatches.removeItemsAt(index);
4031 mpClientInterface->onAudioPatchListUpdate();
4032 }
4033
Eric Laurente552edb2014-03-10 17:42:56 -07004034 AudioParameter param;
4035 param.add(String8("closing"), String8("true"));
4036 mpClientInterface->setParameters(output, param.toString());
4037
4038 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004039 mOutputs.removeItem(output);
4040 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004041}
4042
4043void AudioPolicyManager::closeInput(audio_io_handle_t input)
4044{
4045 ALOGV("closeInput(%d)", input);
4046
4047 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4048 if (inputDesc == NULL) {
4049 ALOGW("closeInput() unknown input %d", input);
4050 return;
4051 }
4052
Eric Laurent6a94d692014-05-20 11:18:06 -07004053 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004054
4055 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4056 if (index >= 0) {
4057 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4058 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4059 mAudioPatches.removeItemsAt(index);
4060 mpClientInterface->onAudioPatchListUpdate();
4061 }
4062
4063 mpClientInterface->closeInput(input);
4064 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004065}
4066
Eric Laurente0720872014-03-11 09:30:41 -07004067SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07004068 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004069{
4070 SortedVector<audio_io_handle_t> outputs;
4071
4072 ALOGVV("getOutputsForDevice() device %04x", device);
4073 for (size_t i = 0; i < openOutputs.size(); i++) {
4074 ALOGVV("output %d isDuplicated=%d device=%04x",
4075 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
4076 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4077 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4078 outputs.add(openOutputs.keyAt(i));
4079 }
4080 }
4081 return outputs;
4082}
4083
Eric Laurente0720872014-03-11 09:30:41 -07004084bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07004085 SortedVector<audio_io_handle_t>& outputs2)
4086{
4087 if (outputs1.size() != outputs2.size()) {
4088 return false;
4089 }
4090 for (size_t i = 0; i < outputs1.size(); i++) {
4091 if (outputs1[i] != outputs2[i]) {
4092 return false;
4093 }
4094 }
4095 return true;
4096}
4097
Eric Laurente0720872014-03-11 09:30:41 -07004098void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004099{
4100 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4101 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4102 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4103 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4104
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004105 // also take into account external policy-related changes: add all outputs which are
4106 // associated with policies in the "before" and "after" output vectors
4107 ALOGVV("checkOutputForStrategy(): policy related outputs");
4108 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
4109 const sp<AudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
4110 if (desc != 0 && desc->mPolicyMix != NULL) {
4111 srcOutputs.add(desc->mIoHandle);
4112 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4113 }
4114 }
4115 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
4116 const sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4117 if (desc != 0 && desc->mPolicyMix != NULL) {
4118 dstOutputs.add(desc->mIoHandle);
4119 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4120 }
4121 }
4122
Eric Laurente552edb2014-03-10 17:42:56 -07004123 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4124 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4125 strategy, srcOutputs[0], dstOutputs[0]);
4126 // mute strategy while moving tracks from one output to another
4127 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004128 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004129 if (desc->isStrategyActive(strategy)) {
4130 setStrategyMute(strategy, true, srcOutputs[i]);
4131 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
4132 }
4133 }
4134
4135 // Move effects associated to this strategy from previous output to new output
4136 if (strategy == STRATEGY_MEDIA) {
4137 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4138 SortedVector<audio_io_handle_t> moved;
4139 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004140 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4141 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4142 effectDesc->mIo != fxOutput) {
4143 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004144 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4145 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004146 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004147 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004148 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004149 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004150 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004151 }
4152 }
4153 }
4154 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004155 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004156 if (i == AUDIO_STREAM_PATCH) {
4157 continue;
4158 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004159 if (getStrategy((audio_stream_type_t)i) == strategy) {
4160 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004161 }
4162 }
4163 }
4164}
4165
Eric Laurente0720872014-03-11 09:30:41 -07004166void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004167{
Jon Eklund966095e2014-09-09 15:39:49 -05004168 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4169 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004170 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05004171 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4172 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004173 checkOutputForStrategy(STRATEGY_SONIFICATION);
4174 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004175 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004176 checkOutputForStrategy(STRATEGY_MEDIA);
4177 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004178 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004179}
4180
Eric Laurente0720872014-03-11 09:30:41 -07004181audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07004182{
Eric Laurente552edb2014-03-10 17:42:56 -07004183 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004184 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004185 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
4186 return mOutputs.keyAt(i);
4187 }
4188 }
4189
4190 return 0;
4191}
4192
Eric Laurente0720872014-03-11 09:30:41 -07004193void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004194{
Eric Laurente552edb2014-03-10 17:42:56 -07004195 audio_io_handle_t a2dpOutput = getA2dpOutput();
4196 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004197 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004198 return;
4199 }
4200
Eric Laurent3a4311c2014-03-17 12:00:47 -07004201 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004202 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4203 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4204 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004205 // suspend A2DP output if:
4206 // (NOT already suspended) &&
4207 // ((SCO device is connected &&
4208 // (forced usage for communication || for record is SCO))) ||
4209 // (phone state is ringing || in call)
4210 //
4211 // restore A2DP output if:
4212 // (Already suspended) &&
4213 // ((SCO device is NOT connected ||
4214 // (forced usage NOT for communication && NOT for record is SCO))) &&
4215 // (phone state is NOT ringing && NOT in call)
4216 //
4217 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004218 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004219 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
4220 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
4221 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
4222 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004223
4224 mpClientInterface->restoreOutput(a2dpOutput);
4225 mA2dpSuspended = false;
4226 }
4227 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004228 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004229 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4230 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
4231 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
4232 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004233
4234 mpClientInterface->suspendOutput(a2dpOutput);
4235 mA2dpSuspended = true;
4236 }
4237 }
4238}
4239
Eric Laurent1c333e22014-05-20 10:48:17 -07004240audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004241{
4242 audio_devices_t device = AUDIO_DEVICE_NONE;
4243
Eric Laurent1f2f2232014-06-02 12:01:23 -07004244 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004245
4246 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4247 if (index >= 0) {
4248 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4249 if (patchDesc->mUid != mUidCached) {
4250 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4251 outputDesc->device(), outputDesc->mPatchHandle);
4252 return outputDesc->device();
4253 }
4254 }
4255
Eric Laurente552edb2014-03-10 17:42:56 -07004256 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004257 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004258 // use device for strategy enforced audible
4259 // 2: we are in call or the strategy phone is active on the output:
4260 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004261 // 3: the strategy for enforced audible is active but not enforced on the output:
4262 // use the device for strategy enforced audible
4263 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004264 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05004265 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004266 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004267 // 6: the strategy accessibility is active on the output:
4268 // use device for strategy accessibility
4269 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004270 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004271 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004272 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004273 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004274 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05004275 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
4276 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004277 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4278 } else if (isInCall() ||
4279 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
4280 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05004281 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
4282 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004283 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
4284 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
4285 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
4286 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004287 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
4288 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004289 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
4290 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
4291 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
4292 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004293 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
4294 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004295 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
4296 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004297 }
4298
Eric Laurent1c333e22014-05-20 10:48:17 -07004299 ALOGV("getNewOutputDevice() selected device %x", device);
4300 return device;
4301}
4302
4303audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4304{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004305 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004306
4307 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4308 if (index >= 0) {
4309 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4310 if (patchDesc->mUid != mUidCached) {
4311 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4312 inputDesc->mDevice, inputDesc->mPatchHandle);
4313 return inputDesc->mDevice;
4314 }
4315 }
4316
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004317 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07004318
4319 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004320 return device;
4321}
4322
Eric Laurente0720872014-03-11 09:30:41 -07004323uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004324 return (uint32_t)getStrategy(stream);
4325}
4326
Eric Laurente0720872014-03-11 09:30:41 -07004327audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004328 // By checking the range of stream before calling getStrategy, we avoid
4329 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4330 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004331 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004332 return AUDIO_DEVICE_NONE;
4333 }
4334 audio_devices_t devices;
4335 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
4336 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4337 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4338 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004339 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07004340 if (outputDesc->isStrategyActive(strategy)) {
4341 devices = outputDesc->device();
4342 break;
4343 }
Eric Laurente552edb2014-03-10 17:42:56 -07004344 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004345
4346 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4347 and doesn't really need to.*/
4348 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4349 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4350 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4351 }
4352
Eric Laurente552edb2014-03-10 17:42:56 -07004353 return devices;
4354}
4355
Eric Laurente0720872014-03-11 09:30:41 -07004356AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004357 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004358
4359 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4360
Eric Laurente552edb2014-03-10 17:42:56 -07004361 // stream to strategy mapping
4362 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004363 case AUDIO_STREAM_VOICE_CALL:
4364 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004365 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004366 case AUDIO_STREAM_RING:
4367 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004368 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004369 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004370 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004371 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004372 return STRATEGY_DTMF;
4373 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004374 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004375 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004376 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4377 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004378 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004379 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004380 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004381 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004382 case AUDIO_STREAM_TTS:
4383 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004384 case AUDIO_STREAM_ACCESSIBILITY:
4385 return STRATEGY_ACCESSIBILITY;
4386 case AUDIO_STREAM_REROUTING:
4387 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004388 }
4389}
4390
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004391uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4392 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004393 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4394 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4395 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004396 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4397 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4398 }
4399
4400 // usage to strategy mapping
4401 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004402 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4403 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4404 return (uint32_t) STRATEGY_SONIFICATION;
4405 }
4406 if (isInCall()) {
4407 return (uint32_t) STRATEGY_PHONE;
4408 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004409 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004410
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004411 case AUDIO_USAGE_MEDIA:
4412 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004413 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4414 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4415 return (uint32_t) STRATEGY_MEDIA;
4416
4417 case AUDIO_USAGE_VOICE_COMMUNICATION:
4418 return (uint32_t) STRATEGY_PHONE;
4419
4420 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4421 return (uint32_t) STRATEGY_DTMF;
4422
4423 case AUDIO_USAGE_ALARM:
4424 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4425 return (uint32_t) STRATEGY_SONIFICATION;
4426
4427 case AUDIO_USAGE_NOTIFICATION:
4428 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4429 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4430 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4431 case AUDIO_USAGE_NOTIFICATION_EVENT:
4432 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4433
4434 case AUDIO_USAGE_UNKNOWN:
4435 default:
4436 return (uint32_t) STRATEGY_MEDIA;
4437 }
4438}
4439
Eric Laurente0720872014-03-11 09:30:41 -07004440void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004441 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004442 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004443 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4444 updateDevicesAndOutputs();
4445 break;
4446 default:
4447 break;
4448 }
4449}
4450
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004451bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4452 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4453 if (s == (size_t) streamToIgnore) {
4454 continue;
4455 }
4456 for (size_t i = 0; i < mOutputs.size(); i++) {
4457 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4458 if (outputDesc->mRefCount[s] != 0) {
4459 return true;
4460 }
4461 }
4462 }
4463 return false;
4464}
4465
4466uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4467 switch(event) {
4468 case STARTING_OUTPUT:
4469 mBeaconMuteRefCount++;
4470 break;
4471 case STOPPING_OUTPUT:
4472 if (mBeaconMuteRefCount > 0) {
4473 mBeaconMuteRefCount--;
4474 }
4475 break;
4476 case STARTING_BEACON:
4477 mBeaconPlayingRefCount++;
4478 break;
4479 case STOPPING_BEACON:
4480 if (mBeaconPlayingRefCount > 0) {
4481 mBeaconPlayingRefCount--;
4482 }
4483 break;
4484 }
4485
4486 if (mBeaconMuteRefCount > 0) {
4487 // any playback causes beacon to be muted
4488 return setBeaconMute(true);
4489 } else {
4490 // no other playback: unmute when beacon starts playing, mute when it stops
4491 return setBeaconMute(mBeaconPlayingRefCount == 0);
4492 }
4493}
4494
4495uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4496 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4497 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4498 // keep track of muted state to avoid repeating mute/unmute operations
4499 if (mBeaconMuted != mute) {
4500 // mute/unmute AUDIO_STREAM_TTS on all outputs
4501 ALOGV("\t muting %d", mute);
4502 uint32_t maxLatency = 0;
4503 for (size_t i = 0; i < mOutputs.size(); i++) {
4504 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4505 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4506 desc->mIoHandle,
4507 0 /*delay*/, AUDIO_DEVICE_NONE);
4508 const uint32_t latency = desc->latency() * 2;
4509 if (latency > maxLatency) {
4510 maxLatency = latency;
4511 }
4512 }
4513 mBeaconMuted = mute;
4514 return maxLatency;
4515 }
4516 return 0;
4517}
4518
Eric Laurente0720872014-03-11 09:30:41 -07004519audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004520 bool fromCache)
4521{
4522 uint32_t device = AUDIO_DEVICE_NONE;
4523
4524 if (fromCache) {
4525 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4526 strategy, mDeviceForStrategy[strategy]);
4527 return mDeviceForStrategy[strategy];
4528 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004529 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004530 switch (strategy) {
4531
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004532 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4533 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4534 if (!device) {
4535 ALOGE("getDeviceForStrategy() no device found for "\
4536 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4537 }
4538 break;
4539
Eric Laurente552edb2014-03-10 17:42:56 -07004540 case STRATEGY_SONIFICATION_RESPECTFUL:
4541 if (isInCall()) {
4542 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004543 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004544 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4545 // while media is playing on a remote device, use the the sonification behavior.
4546 // Note that we test this usecase before testing if media is playing because
4547 // the isStreamActive() method only informs about the activity of a stream, not
4548 // if it's for local playback. Note also that we use the same delay between both tests
4549 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004550 //user "safe" speaker if available instead of normal speaker to avoid triggering
4551 //other acoustic safety mechanisms for notification
4552 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4553 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004554 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004555 // while media is playing (or has recently played), use the same device
4556 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4557 } else {
4558 // when media is not playing anymore, fall back on the sonification behavior
4559 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004560 //user "safe" speaker if available instead of normal speaker to avoid triggering
4561 //other acoustic safety mechanisms for notification
4562 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4563 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004564 }
4565
4566 break;
4567
4568 case STRATEGY_DTMF:
4569 if (!isInCall()) {
4570 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4571 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4572 break;
4573 }
4574 // when in call, DTMF and PHONE strategies follow the same rules
4575 // FALL THROUGH
4576
4577 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004578 // Force use of only devices on primary output if:
4579 // - in call AND
4580 // - cannot route from voice call RX OR
4581 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4582 if (mPhoneState == AUDIO_MODE_IN_CALL) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004583 audio_devices_t txDevice =
4584 getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -07004585 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4586 if (((mAvailableInputDevices.types() &
4587 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4588 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004589 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004590 AUDIO_DEVICE_API_VERSION_3_0))) {
4591 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4592 }
4593 }
Eric Laurente552edb2014-03-10 17:42:56 -07004594 // for phone strategy, we first consider the forced use and then the available devices by order
4595 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004596 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4597 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004598 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004599 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004600 if (device) break;
4601 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004602 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004603 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004604 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004605 if (device) break;
4606 // if SCO device is requested but no SCO device is available, fall back to default case
4607 // FALL THROUGH
4608
4609 default: // FORCE_NONE
4610 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004611 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004612 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004613 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004614 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004615 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004616 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004617 if (device) break;
4618 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004619 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004620 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004621 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004622 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004623 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4624 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004625 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004626 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004627 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004628 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004629 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004630 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004631 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004632 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004633 if (device) break;
4634 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004635 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004636 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004637 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004638 if (device == AUDIO_DEVICE_NONE) {
4639 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4640 }
4641 break;
4642
Eric Laurent3b73df72014-03-11 09:06:29 -07004643 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004644 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4645 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004646 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004647 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004648 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004649 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004650 if (device) break;
4651 }
Eric Laurentcd71a692014-12-16 12:01:12 -08004652 if (!isInCall()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004653 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004654 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004655 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004656 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004657 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004658 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004659 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004660 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004661 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004662 if (device) break;
4663 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004664 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4665 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004666 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004667 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004668 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004669 if (device == AUDIO_DEVICE_NONE) {
4670 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4671 }
4672 break;
4673 }
4674 break;
4675
4676 case STRATEGY_SONIFICATION:
4677
4678 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4679 // handleIncallSonification().
4680 if (isInCall()) {
4681 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4682 break;
4683 }
4684 // FALL THROUGH
4685
4686 case STRATEGY_ENFORCED_AUDIBLE:
4687 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4688 // except:
4689 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4690 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4691
4692 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004693 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004694 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004695 if (device == AUDIO_DEVICE_NONE) {
4696 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4697 }
4698 }
4699 // The second device used for sonification is the same as the device used by media strategy
4700 // FALL THROUGH
4701
Eric Laurent223fd5c2014-11-11 13:43:36 -08004702 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4703 case STRATEGY_ACCESSIBILITY:
Eric Laurent066ceec2014-11-25 12:35:01 -08004704 if (strategy == STRATEGY_ACCESSIBILITY) {
4705 // do not route accessibility prompts to a digital output currently configured with a
4706 // compressed format as they would likely not be mixed and dropped.
4707 for (size_t i = 0; i < mOutputs.size(); i++) {
4708 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4709 audio_devices_t devices = desc->device() &
4710 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4711 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4712 devices != AUDIO_DEVICE_NONE) {
4713 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4714 }
4715 }
4716 }
4717 // FALL THROUGH
4718
Eric Laurent223fd5c2014-11-11 13:43:36 -08004719 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004720 case STRATEGY_MEDIA: {
4721 uint32_t device2 = AUDIO_DEVICE_NONE;
4722 if (strategy != STRATEGY_SONIFICATION) {
4723 // no sonification on remote submix (e.g. WFD)
Eric Laurent275e8e92014-11-30 15:14:47 -08004724 if (mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, String8("0")) != 0) {
4725 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
4726 }
Eric Laurente552edb2014-03-10 17:42:56 -07004727 }
4728 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004729 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004730 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004731 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004732 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004733 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004734 }
4735 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004736 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004737 }
4738 }
Hochi Huang327cb702014-09-21 09:47:31 +08004739 if ((device2 == AUDIO_DEVICE_NONE) &&
4740 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4741 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4742 }
Eric Laurente552edb2014-03-10 17:42:56 -07004743 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004744 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004745 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004746 if ((device2 == AUDIO_DEVICE_NONE)) {
4747 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4748 }
Eric Laurente552edb2014-03-10 17:42:56 -07004749 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004750 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004751 }
4752 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004753 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004754 }
4755 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004756 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004757 }
4758 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004759 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004760 }
4761 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4762 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004763 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004764 }
4765 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004766 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004767 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004768 }
4769 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004770 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004771 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004772 int device3 = AUDIO_DEVICE_NONE;
4773 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004774 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004775 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4776 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004777 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004778 }
Eric Laurente552edb2014-03-10 17:42:56 -07004779
Jungshik Jang839e4f32014-06-26 17:23:40 +09004780 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004781 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4782 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4783 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004784
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004785 // If hdmi system audio mode is on, remove speaker out of output list.
4786 if ((strategy == STRATEGY_MEDIA) &&
4787 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4788 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4789 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4790 }
4791
Eric Laurente552edb2014-03-10 17:42:56 -07004792 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004793 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004794 if (device == AUDIO_DEVICE_NONE) {
4795 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4796 }
4797 } break;
4798
4799 default:
4800 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4801 break;
4802 }
4803
4804 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4805 return device;
4806}
4807
Eric Laurente0720872014-03-11 09:30:41 -07004808void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004809{
4810 for (int i = 0; i < NUM_STRATEGIES; i++) {
4811 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4812 }
4813 mPreviousOutputs = mOutputs;
4814}
4815
Eric Laurent1f2f2232014-06-02 12:01:23 -07004816uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004817 audio_devices_t prevDevice,
4818 uint32_t delayMs)
4819{
4820 // mute/unmute strategies using an incompatible device combination
4821 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4822 // if unmuting, unmute only after the specified delay
4823 if (outputDesc->isDuplicated()) {
4824 return 0;
4825 }
4826
4827 uint32_t muteWaitMs = 0;
4828 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004829 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004830
4831 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4832 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004833 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004834 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4835 bool doMute = false;
4836
4837 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4838 doMute = true;
4839 outputDesc->mStrategyMutedByDevice[i] = true;
4840 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4841 doMute = true;
4842 outputDesc->mStrategyMutedByDevice[i] = false;
4843 }
Eric Laurent99401132014-05-07 19:48:15 -07004844 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004845 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004846 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004847 // skip output if it does not share any device with current output
4848 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4849 == AUDIO_DEVICE_NONE) {
4850 continue;
4851 }
4852 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4853 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4854 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4855 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4856 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004857 if (mute) {
4858 // FIXME: should not need to double latency if volume could be applied
4859 // immediately by the audioflinger mixer. We must account for the delay
4860 // between now and the next time the audioflinger thread for this output
4861 // will process a buffer (which corresponds to one buffer size,
4862 // usually 1/2 or 1/4 of the latency).
4863 if (muteWaitMs < desc->latency() * 2) {
4864 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004865 }
4866 }
4867 }
4868 }
4869 }
4870 }
4871
Eric Laurent99401132014-05-07 19:48:15 -07004872 // temporary mute output if device selection changes to avoid volume bursts due to
4873 // different per device volumes
4874 if (outputDesc->isActive() && (device != prevDevice)) {
4875 if (muteWaitMs < outputDesc->latency() * 2) {
4876 muteWaitMs = outputDesc->latency() * 2;
4877 }
4878 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4879 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004880 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004881 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004882 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004883 muteWaitMs *2, device);
4884 }
4885 }
4886 }
4887
Eric Laurente552edb2014-03-10 17:42:56 -07004888 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4889 if (muteWaitMs > delayMs) {
4890 muteWaitMs -= delayMs;
4891 usleep(muteWaitMs * 1000);
4892 return muteWaitMs;
4893 }
4894 return 0;
4895}
4896
Eric Laurente0720872014-03-11 09:30:41 -07004897uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004898 audio_devices_t device,
4899 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004900 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004901 audio_patch_handle_t *patchHandle,
4902 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004903{
4904 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004905 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004906 AudioParameter param;
4907 uint32_t muteWaitMs;
4908
4909 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004910 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4911 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004912 return muteWaitMs;
4913 }
4914 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4915 // output profile
4916 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004917 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004918 return 0;
4919 }
4920
4921 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004922 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004923
4924 audio_devices_t prevDevice = outputDesc->mDevice;
4925
4926 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4927
4928 if (device != AUDIO_DEVICE_NONE) {
4929 outputDesc->mDevice = device;
4930 }
4931 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4932
4933 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004934 // the requested device is AUDIO_DEVICE_NONE
4935 // OR the requested device is the same as current device
4936 // AND force is not specified
4937 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004938 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004939 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4940 outputDesc->mPatchHandle != 0) {
4941 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4942 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004943 return muteWaitMs;
4944 }
4945
4946 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004947
Eric Laurente552edb2014-03-10 17:42:56 -07004948 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004949 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004950 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004951 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004952 DeviceVector deviceList = (address == NULL) ?
4953 mAvailableOutputDevices.getDevicesFromType(device)
4954 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004955 if (!deviceList.isEmpty()) {
4956 struct audio_patch patch;
4957 outputDesc->toAudioPortConfig(&patch.sources[0]);
4958 patch.num_sources = 1;
4959 patch.num_sinks = 0;
4960 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4961 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004962 patch.num_sinks++;
4963 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004964 ssize_t index;
4965 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4966 index = mAudioPatches.indexOfKey(*patchHandle);
4967 } else {
4968 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4969 }
4970 sp< AudioPatch> patchDesc;
4971 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4972 if (index >= 0) {
4973 patchDesc = mAudioPatches.valueAt(index);
4974 afPatchHandle = patchDesc->mAfPatchHandle;
4975 }
4976
Eric Laurent1c333e22014-05-20 10:48:17 -07004977 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004978 &afPatchHandle,
4979 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004980 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4981 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004982 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004983 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004984 if (index < 0) {
4985 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4986 &patch, mUidCached);
4987 addAudioPatch(patchDesc->mHandle, patchDesc);
4988 } else {
4989 patchDesc->mPatch = patch;
4990 }
4991 patchDesc->mAfPatchHandle = afPatchHandle;
4992 patchDesc->mUid = mUidCached;
4993 if (patchHandle) {
4994 *patchHandle = patchDesc->mHandle;
4995 }
4996 outputDesc->mPatchHandle = patchDesc->mHandle;
4997 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004998 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004999 }
5000 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005001
5002 // inform all input as well
5003 for (size_t i = 0; i < mInputs.size(); i++) {
5004 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
5005 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
5006 AudioParameter inputCmd = AudioParameter();
5007 ALOGV("%s: inform input %d of device:%d", __func__,
5008 inputDescriptor->mIoHandle, device);
5009 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5010 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5011 inputCmd.toString(),
5012 delayMs);
5013 }
5014 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005015 }
Eric Laurente552edb2014-03-10 17:42:56 -07005016
5017 // update stream volumes according to new device
5018 applyStreamVolumes(output, device, delayMs);
5019
5020 return muteWaitMs;
5021}
5022
Eric Laurent1c333e22014-05-20 10:48:17 -07005023status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07005024 int delayMs,
5025 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005026{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005027 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07005028 ssize_t index;
5029 if (patchHandle) {
5030 index = mAudioPatches.indexOfKey(*patchHandle);
5031 } else {
5032 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
5033 }
5034 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005035 return INVALID_OPERATION;
5036 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005037 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5038 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005039 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
5040 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005041 removeAudioPatch(patchDesc->mHandle);
5042 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005043 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005044 return status;
5045}
5046
5047status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5048 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005049 bool force,
5050 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005051{
5052 status_t status = NO_ERROR;
5053
Eric Laurent1f2f2232014-06-02 12:01:23 -07005054 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005055 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5056 inputDesc->mDevice = device;
5057
5058 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5059 if (!deviceList.isEmpty()) {
5060 struct audio_patch patch;
5061 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005062 // AUDIO_SOURCE_HOTWORD is for internal use only:
5063 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005064 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
5065 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005066 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5067 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005068 patch.num_sinks = 1;
5069 //only one input device for now
5070 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005071 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005072 ssize_t index;
5073 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5074 index = mAudioPatches.indexOfKey(*patchHandle);
5075 } else {
5076 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5077 }
5078 sp< AudioPatch> patchDesc;
5079 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5080 if (index >= 0) {
5081 patchDesc = mAudioPatches.valueAt(index);
5082 afPatchHandle = patchDesc->mAfPatchHandle;
5083 }
5084
Eric Laurent1c333e22014-05-20 10:48:17 -07005085 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005086 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005087 0);
5088 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005089 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005090 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005091 if (index < 0) {
5092 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
5093 &patch, mUidCached);
5094 addAudioPatch(patchDesc->mHandle, patchDesc);
5095 } else {
5096 patchDesc->mPatch = patch;
5097 }
5098 patchDesc->mAfPatchHandle = afPatchHandle;
5099 patchDesc->mUid = mUidCached;
5100 if (patchHandle) {
5101 *patchHandle = patchDesc->mHandle;
5102 }
5103 inputDesc->mPatchHandle = patchDesc->mHandle;
5104 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005105 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005106 }
5107 }
5108 }
5109 return status;
5110}
5111
Eric Laurent6a94d692014-05-20 11:18:06 -07005112status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5113 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005114{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005115 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005116 ssize_t index;
5117 if (patchHandle) {
5118 index = mAudioPatches.indexOfKey(*patchHandle);
5119 } else {
5120 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5121 }
5122 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005123 return INVALID_OPERATION;
5124 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005125 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5126 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005127 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
5128 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005129 removeAudioPatch(patchDesc->mHandle);
5130 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005131 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005132 return status;
5133}
5134
5135sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08005136 String8 address,
Glenn Kastencbd48022014-07-24 13:46:44 -07005137 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07005138 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005139 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07005140 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005141{
5142 // Choose an input profile based on the requested capture parameters: select the first available
5143 // profile supporting all requested parameters.
5144
5145 for (size_t i = 0; i < mHwModules.size(); i++)
5146 {
5147 if (mHwModules[i]->mHandle == 0) {
5148 continue;
5149 }
5150 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5151 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005152 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005153 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005154 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005155 &samplingRate /*updatedSamplingRate*/,
5156 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005157
Eric Laurente552edb2014-03-10 17:42:56 -07005158 return profile;
5159 }
5160 }
5161 }
5162 return NULL;
5163}
5164
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005165
5166audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
Eric Laurentc722f302014-12-10 11:21:49 -08005167 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005168{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005169 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5170 ~AUDIO_DEVICE_BIT_IN;
Eric Laurent275e8e92014-11-30 15:14:47 -08005171
5172 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
5173 if (mPolicyMixes[i]->mMix.mMixType != MIX_TYPE_RECORDERS) {
5174 continue;
5175 }
5176 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
5177 if ((RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5178 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource == inputSource) ||
5179 (RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5180 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource != inputSource)) {
5181 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurentc722f302014-12-10 11:21:49 -08005182 if (policyMix != NULL) {
5183 *policyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005184 }
5185 return AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5186 }
5187 break;
5188 }
5189 }
5190 }
5191
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005192 return getDeviceForInputSource(inputSource);
5193}
5194
5195audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5196{
5197 uint32_t device = AUDIO_DEVICE_NONE;
5198 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5199 ~AUDIO_DEVICE_BIT_IN;
5200
Eric Laurente552edb2014-03-10 17:42:56 -07005201 switch (inputSource) {
5202 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005203 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005204 device = AUDIO_DEVICE_IN_VOICE_CALL;
5205 break;
5206 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005207 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005208
5209 case AUDIO_SOURCE_DEFAULT:
5210 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07005211 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
5212 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentdc136ff2014-12-16 12:24:18 -08005213 } else if ((mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO) &&
5214 (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET)) {
5215 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurentc2730ba2014-07-20 15:47:07 -07005216 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5217 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5218 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5219 device = AUDIO_DEVICE_IN_USB_DEVICE;
5220 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5221 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005222 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005223 break;
5224
5225 case AUDIO_SOURCE_VOICE_COMMUNICATION:
5226 // Allow only use of devices on primary input if in call and HAL does not support routing
5227 // to voice call path.
5228 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
5229 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
5230 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
5231 }
5232
5233 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
5234 case AUDIO_POLICY_FORCE_BT_SCO:
5235 // if SCO device is requested but no SCO device is available, fall back to default case
5236 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
5237 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
5238 break;
5239 }
5240 // FALL THROUGH
5241
5242 default: // FORCE_NONE
5243 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5244 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5245 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5246 device = AUDIO_DEVICE_IN_USB_DEVICE;
5247 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5248 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5249 }
5250 break;
5251
5252 case AUDIO_POLICY_FORCE_SPEAKER:
5253 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
5254 device = AUDIO_DEVICE_IN_BACK_MIC;
5255 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5256 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5257 }
5258 break;
5259 }
5260 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005261
Eric Laurente552edb2014-03-10 17:42:56 -07005262 case AUDIO_SOURCE_VOICE_RECOGNITION:
5263 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07005264 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005265 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005266 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005267 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005268 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07005269 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5270 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005271 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005272 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5273 }
5274 break;
5275 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005276 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005277 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005278 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005279 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5280 }
5281 break;
5282 case AUDIO_SOURCE_VOICE_DOWNLINK:
5283 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005284 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005285 device = AUDIO_DEVICE_IN_VOICE_CALL;
5286 }
5287 break;
5288 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005289 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07005290 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5291 }
5292 break;
Hochi Huang327cb702014-09-21 09:47:31 +08005293 case AUDIO_SOURCE_FM_TUNER:
5294 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
5295 device = AUDIO_DEVICE_IN_FM_TUNER;
5296 }
5297 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005298 default:
5299 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
5300 break;
5301 }
5302 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
5303 return device;
5304}
5305
Eric Laurente0720872014-03-11 09:30:41 -07005306bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005307{
5308 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
5309 device &= ~AUDIO_DEVICE_BIT_IN;
5310 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
5311 return true;
5312 }
5313 return false;
5314}
5315
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005316bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005317 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL & ~AUDIO_DEVICE_BIT_IN) != 0);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005318}
5319
Eric Laurente0720872014-03-11 09:30:41 -07005320audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005321{
5322 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005323 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07005324 if ((input_descriptor->mRefCount > 0)
5325 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
5326 return mInputs.keyAt(i);
5327 }
5328 }
5329 return 0;
5330}
5331
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005332uint32_t AudioPolicyManager::activeInputsCount() const
5333{
5334 uint32_t count = 0;
5335 for (size_t i = 0; i < mInputs.size(); i++) {
5336 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
5337 if (desc->mRefCount > 0) {
Eric Laurenta34c9ce2014-12-19 11:16:32 -08005338 count++;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005339 }
5340 }
5341 return count;
5342}
5343
Eric Laurente552edb2014-03-10 17:42:56 -07005344
Eric Laurente0720872014-03-11 09:30:41 -07005345audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005346{
5347 if (device == AUDIO_DEVICE_NONE) {
5348 // this happens when forcing a route update and no track is active on an output.
5349 // In this case the returned category is not important.
5350 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07005351 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07005352 // Multiple device selection is either:
5353 // - speaker + one other device: give priority to speaker in this case.
5354 // - one A2DP device + another device: happens with duplicated output. In this case
5355 // retain the device on the A2DP output as the other must not correspond to an active
5356 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09005357 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07005358 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
5359 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09005360 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
5361 device = AUDIO_DEVICE_OUT_HDMI_ARC;
5362 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
5363 device = AUDIO_DEVICE_OUT_AUX_LINE;
5364 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
5365 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07005366 } else {
5367 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
5368 }
5369 }
5370
Jon Eklund11c9fb12014-06-23 14:47:03 -05005371 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
5372 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
5373 device = AUDIO_DEVICE_OUT_SPEAKER;
5374
Eric Laurent3b73df72014-03-11 09:06:29 -07005375 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07005376 "getDeviceForVolume() invalid device combination: %08x",
5377 device);
5378
5379 return device;
5380}
5381
Eric Laurente0720872014-03-11 09:30:41 -07005382AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005383{
5384 switch(getDeviceForVolume(device)) {
5385 case AUDIO_DEVICE_OUT_EARPIECE:
5386 return DEVICE_CATEGORY_EARPIECE;
5387 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5388 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5389 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5390 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5391 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5392 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5393 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05005394 case AUDIO_DEVICE_OUT_LINE:
5395 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5396 /*USB? Remote submix?*/
5397 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07005398 case AUDIO_DEVICE_OUT_SPEAKER:
5399 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5400 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005401 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5402 case AUDIO_DEVICE_OUT_USB_DEVICE:
5403 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5404 default:
5405 return DEVICE_CATEGORY_SPEAKER;
5406 }
5407}
5408
Eric Laurent223fd5c2014-11-11 13:43:36 -08005409/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005410float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005411 int indexInUi)
5412{
5413 device_category deviceCategory = getDeviceCategory(device);
5414 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5415
5416 // the volume index in the UI is relative to the min and max volume indices for this stream type
5417 int nbSteps = 1 + curve[VOLMAX].mIndex -
5418 curve[VOLMIN].mIndex;
5419 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5420 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5421
5422 // find what part of the curve this index volume belongs to, or if it's out of bounds
5423 int segment = 0;
5424 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5425 return 0.0f;
5426 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5427 segment = 0;
5428 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5429 segment = 1;
5430 } else if (volIdx <= curve[VOLMAX].mIndex) {
5431 segment = 2;
5432 } else { // out of bounds
5433 return 1.0f;
5434 }
5435
5436 // linear interpolation in the attenuation table in dB
5437 float decibels = curve[segment].mDBAttenuation +
5438 ((float)(volIdx - curve[segment].mIndex)) *
5439 ( (curve[segment+1].mDBAttenuation -
5440 curve[segment].mDBAttenuation) /
5441 ((float)(curve[segment+1].mIndex -
5442 curve[segment].mIndex)) );
5443
5444 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5445
5446 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5447 curve[segment].mIndex, volIdx,
5448 curve[segment+1].mIndex,
5449 curve[segment].mDBAttenuation,
5450 decibels,
5451 curve[segment+1].mDBAttenuation,
5452 amplification);
5453
5454 return amplification;
5455}
5456
Eric Laurente0720872014-03-11 09:30:41 -07005457const AudioPolicyManager::VolumeCurvePoint
5458 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005459 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5460};
5461
Eric Laurente0720872014-03-11 09:30:41 -07005462const AudioPolicyManager::VolumeCurvePoint
5463 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005464 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5465};
5466
Eric Laurente0720872014-03-11 09:30:41 -07005467const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005468 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5469 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5470};
5471
5472const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005473 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005474 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5475};
5476
Eric Laurente0720872014-03-11 09:30:41 -07005477const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005478 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005479 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005480};
5481
5482const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005483 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005484 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5485};
5486
Eric Laurente0720872014-03-11 09:30:41 -07005487const AudioPolicyManager::VolumeCurvePoint
5488 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005489 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5490};
5491
5492// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5493// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5494// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5495// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5496
Eric Laurente0720872014-03-11 09:30:41 -07005497const AudioPolicyManager::VolumeCurvePoint
5498 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005499 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5500};
5501
Eric Laurente0720872014-03-11 09:30:41 -07005502const AudioPolicyManager::VolumeCurvePoint
5503 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005504 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5505};
5506
Eric Laurente0720872014-03-11 09:30:41 -07005507const AudioPolicyManager::VolumeCurvePoint
5508 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005509 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5510};
5511
Eric Laurente0720872014-03-11 09:30:41 -07005512const AudioPolicyManager::VolumeCurvePoint
5513 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005514 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5515};
5516
Eric Laurente0720872014-03-11 09:30:41 -07005517const AudioPolicyManager::VolumeCurvePoint
5518 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005519 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5520};
5521
Eric Laurente0720872014-03-11 09:30:41 -07005522const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005523 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5524 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5525};
5526
5527const AudioPolicyManager::VolumeCurvePoint
5528 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5529 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5530};
5531
5532const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005533 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5534 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5535};
5536
5537const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005538 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5539 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005540 { // AUDIO_STREAM_VOICE_CALL
5541 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5542 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005543 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5544 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005545 },
5546 { // AUDIO_STREAM_SYSTEM
5547 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5548 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005549 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5550 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005551 },
5552 { // AUDIO_STREAM_RING
5553 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5554 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005555 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5556 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005557 },
5558 { // AUDIO_STREAM_MUSIC
5559 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5560 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005561 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5562 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005563 },
5564 { // AUDIO_STREAM_ALARM
5565 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5566 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005567 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5568 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005569 },
5570 { // AUDIO_STREAM_NOTIFICATION
5571 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5572 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005573 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5574 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005575 },
5576 { // AUDIO_STREAM_BLUETOOTH_SCO
5577 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5578 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005579 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5580 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005581 },
5582 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5583 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5584 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005585 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5586 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005587 },
5588 { // AUDIO_STREAM_DTMF
5589 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5590 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005591 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5592 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005593 },
5594 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005595 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5596 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5597 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5598 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5599 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005600 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005601 { // AUDIO_STREAM_ACCESSIBILITY
5602 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5603 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5604 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5605 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5606 },
5607 { // AUDIO_STREAM_REROUTING
5608 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5609 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5610 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5611 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5612 },
5613 { // AUDIO_STREAM_PATCH
5614 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5615 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5616 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5617 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5618 },
Eric Laurente552edb2014-03-10 17:42:56 -07005619};
5620
Eric Laurente0720872014-03-11 09:30:41 -07005621void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005622{
5623 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5624 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5625 mStreams[i].mVolumeCurve[j] =
5626 sVolumeProfiles[i][j];
5627 }
5628 }
5629
5630 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5631 if (mSpeakerDrcEnabled) {
5632 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5633 sDefaultSystemVolumeCurveDrc;
5634 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5635 sSpeakerSonificationVolumeCurveDrc;
5636 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5637 sSpeakerSonificationVolumeCurveDrc;
5638 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5639 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005640 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5641 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005642 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5643 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005644 }
5645}
5646
Eric Laurente0720872014-03-11 09:30:41 -07005647float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005648 int index,
5649 audio_io_handle_t output,
5650 audio_devices_t device)
5651{
5652 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005653 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005654 StreamDescriptor &streamDesc = mStreams[stream];
5655
5656 if (device == AUDIO_DEVICE_NONE) {
5657 device = outputDesc->device();
5658 }
5659
Eric Laurente552edb2014-03-10 17:42:56 -07005660 volume = volIndexToAmpl(device, streamDesc, index);
5661
5662 // if a headset is connected, apply the following rules to ring tones and notifications
5663 // to avoid sound level bursts in user's ears:
5664 // - always attenuate ring tones and notifications volume by 6dB
5665 // - if music is playing, always limit the volume to current music volume,
5666 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005667 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005668 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5669 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5670 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5671 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5672 ((stream_strategy == STRATEGY_SONIFICATION)
5673 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005674 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005675 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005676 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005677 streamDesc.mCanBeMuted) {
5678 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5679 // when the phone is ringing we must consider that music could have been paused just before
5680 // by the music application and behave as if music was active if the last music track was
5681 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005682 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005683 mLimitRingtoneVolume) {
5684 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005685 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5686 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005687 output,
5688 musicDevice);
5689 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5690 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5691 if (volume > minVol) {
5692 volume = minVol;
5693 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5694 }
5695 }
5696 }
5697
5698 return volume;
5699}
5700
Eric Laurente0720872014-03-11 09:30:41 -07005701status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005702 int index,
5703 audio_io_handle_t output,
5704 audio_devices_t device,
5705 int delayMs,
5706 bool force)
5707{
5708
5709 // do not change actual stream volume if the stream is muted
5710 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5711 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5712 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5713 return NO_ERROR;
5714 }
5715
5716 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005717 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5718 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5719 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5720 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005721 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005722 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005723 return INVALID_OPERATION;
5724 }
5725
5726 float volume = computeVolume(stream, index, output, device);
Eric Laurent275e8e92014-11-30 15:14:47 -08005727 // unit gain if rerouting to external policy
5728 if (device == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
5729 ssize_t index = mOutputs.indexOfKey(output);
5730 if (index >= 0) {
5731 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurentc722f302014-12-10 11:21:49 -08005732 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005733 ALOGV("max gain when rerouting for output=%d", output);
5734 volume = 1.0f;
5735 }
5736 }
5737
5738 }
Eric Laurente552edb2014-03-10 17:42:56 -07005739 // We actually change the volume if:
5740 // - the float value returned by computeVolume() changed
5741 // - the force flag is set
5742 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5743 force) {
5744 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5745 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5746 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5747 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005748 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5749 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005750 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005751 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005752 }
5753
Eric Laurent3b73df72014-03-11 09:06:29 -07005754 if (stream == AUDIO_STREAM_VOICE_CALL ||
5755 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005756 float voiceVolume;
5757 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005758 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005759 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5760 } else {
5761 voiceVolume = 1.0;
5762 }
5763
5764 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5765 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5766 mLastVoiceVolume = voiceVolume;
5767 }
5768 }
5769
5770 return NO_ERROR;
5771}
5772
Eric Laurente0720872014-03-11 09:30:41 -07005773void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005774 audio_devices_t device,
5775 int delayMs,
5776 bool force)
5777{
5778 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5779
Eric Laurent3b73df72014-03-11 09:06:29 -07005780 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005781 if (stream == AUDIO_STREAM_PATCH) {
5782 continue;
5783 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005784 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005785 mStreams[stream].getVolumeIndex(device),
5786 output,
5787 device,
5788 delayMs,
5789 force);
5790 }
5791}
5792
Eric Laurente0720872014-03-11 09:30:41 -07005793void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005794 bool on,
5795 audio_io_handle_t output,
5796 int delayMs,
5797 audio_devices_t device)
5798{
5799 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005800 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005801 if (stream == AUDIO_STREAM_PATCH) {
5802 continue;
5803 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005804 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5805 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005806 }
5807 }
5808}
5809
Eric Laurente0720872014-03-11 09:30:41 -07005810void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005811 bool on,
5812 audio_io_handle_t output,
5813 int delayMs,
5814 audio_devices_t device)
5815{
5816 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005817 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005818 if (device == AUDIO_DEVICE_NONE) {
5819 device = outputDesc->device();
5820 }
5821
5822 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5823 stream, on, output, outputDesc->mMuteCount[stream], device);
5824
5825 if (on) {
5826 if (outputDesc->mMuteCount[stream] == 0) {
5827 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005828 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5829 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005830 checkAndSetVolume(stream, 0, output, device, delayMs);
5831 }
5832 }
5833 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5834 outputDesc->mMuteCount[stream]++;
5835 } else {
5836 if (outputDesc->mMuteCount[stream] == 0) {
5837 ALOGV("setStreamMute() unmuting non muted stream!");
5838 return;
5839 }
5840 if (--outputDesc->mMuteCount[stream] == 0) {
5841 checkAndSetVolume(stream,
5842 streamDesc.getVolumeIndex(device),
5843 output,
5844 device,
5845 delayMs);
5846 }
5847 }
5848}
5849
Eric Laurente0720872014-03-11 09:30:41 -07005850void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005851 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005852{
5853 // if the stream pertains to sonification strategy and we are in call we must
5854 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5855 // in the device used for phone strategy and play the tone if the selected device does not
5856 // interfere with the device used for phone strategy
5857 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5858 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005859 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005860 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5861 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005862 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005863 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5864 stream, starting, outputDesc->mDevice, stateChange);
5865 if (outputDesc->mRefCount[stream]) {
5866 int muteCount = 1;
5867 if (stateChange) {
5868 muteCount = outputDesc->mRefCount[stream];
5869 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005870 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005871 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5872 for (int i = 0; i < muteCount; i++) {
5873 setStreamMute(stream, starting, mPrimaryOutput);
5874 }
5875 } else {
5876 ALOGV("handleIncallSonification() high visibility");
5877 if (outputDesc->device() &
5878 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5879 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5880 for (int i = 0; i < muteCount; i++) {
5881 setStreamMute(stream, starting, mPrimaryOutput);
5882 }
5883 }
5884 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005885 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5886 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005887 } else {
5888 mpClientInterface->stopTone();
5889 }
5890 }
5891 }
5892 }
5893}
5894
Eric Laurente0720872014-03-11 09:30:41 -07005895bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005896{
5897 return isStateInCall(mPhoneState);
5898}
5899
Eric Laurente0720872014-03-11 09:30:41 -07005900bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005901 return ((state == AUDIO_MODE_IN_CALL) ||
5902 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005903}
5904
Eric Laurente0720872014-03-11 09:30:41 -07005905uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005906{
5907 return MAX_EFFECTS_CPU_LOAD;
5908}
5909
Eric Laurente0720872014-03-11 09:30:41 -07005910uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005911{
5912 return MAX_EFFECTS_MEMORY;
5913}
5914
Eric Laurent6a94d692014-05-20 11:18:06 -07005915
Eric Laurente552edb2014-03-10 17:42:56 -07005916// --- AudioOutputDescriptor class implementation
5917
Eric Laurente0720872014-03-11 09:30:41 -07005918AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005919 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005920 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurentc722f302014-12-10 11:21:49 -08005921 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL),
Eric Laurent275e8e92014-11-30 15:14:47 -08005922 mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005923 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5924{
5925 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005926 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005927 mRefCount[i] = 0;
5928 mCurVolume[i] = -1.0;
5929 mMuteCount[i] = 0;
5930 mStopTime[i] = 0;
5931 }
5932 for (int i = 0; i < NUM_STRATEGIES; i++) {
5933 mStrategyMutedByDevice[i] = false;
5934 }
5935 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005936 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005937 mSamplingRate = profile->pickSamplingRate();
5938 mFormat = profile->pickFormat();
5939 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005940 if (profile->mGains.size() > 0) {
5941 profile->mGains[0]->getDefaultConfig(&mGain);
5942 }
Eric Laurente552edb2014-03-10 17:42:56 -07005943 }
5944}
5945
Eric Laurente0720872014-03-11 09:30:41 -07005946audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005947{
5948 if (isDuplicated()) {
5949 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5950 } else {
5951 return mDevice;
5952 }
5953}
5954
Eric Laurente0720872014-03-11 09:30:41 -07005955uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005956{
5957 if (isDuplicated()) {
5958 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5959 } else {
5960 return mLatency;
5961 }
5962}
5963
Eric Laurente0720872014-03-11 09:30:41 -07005964bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005965 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005966{
5967 if (isDuplicated()) {
5968 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5969 } else if (outputDesc->isDuplicated()){
5970 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5971 } else {
5972 return (mProfile->mModule == outputDesc->mProfile->mModule);
5973 }
5974}
5975
Eric Laurente0720872014-03-11 09:30:41 -07005976void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005977 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005978{
5979 // forward usage count change to attached outputs
5980 if (isDuplicated()) {
5981 mOutput1->changeRefCount(stream, delta);
5982 mOutput2->changeRefCount(stream, delta);
5983 }
5984 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005985 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5986 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005987 mRefCount[stream] = 0;
5988 return;
5989 }
5990 mRefCount[stream] += delta;
5991 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5992}
5993
Eric Laurente0720872014-03-11 09:30:41 -07005994audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005995{
5996 if (isDuplicated()) {
5997 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5998 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005999 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07006000 }
6001}
6002
Eric Laurente0720872014-03-11 09:30:41 -07006003bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07006004{
6005 return isStrategyActive(NUM_STRATEGIES, inPastMs);
6006}
6007
Eric Laurente0720872014-03-11 09:30:41 -07006008bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07006009 uint32_t inPastMs,
6010 nsecs_t sysTime) const
6011{
6012 if ((sysTime == 0) && (inPastMs != 0)) {
6013 sysTime = systemTime();
6014 }
Eric Laurent3b73df72014-03-11 09:06:29 -07006015 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08006016 if (i == AUDIO_STREAM_PATCH) {
6017 continue;
6018 }
Eric Laurent3b73df72014-03-11 09:06:29 -07006019 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006020 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07006021 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006022 return true;
6023 }
6024 }
6025 return false;
6026}
6027
Eric Laurente0720872014-03-11 09:30:41 -07006028bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07006029 uint32_t inPastMs,
6030 nsecs_t sysTime) const
6031{
6032 if (mRefCount[stream] != 0) {
6033 return true;
6034 }
6035 if (inPastMs == 0) {
6036 return false;
6037 }
6038 if (sysTime == 0) {
6039 sysTime = systemTime();
6040 }
6041 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
6042 return true;
6043 }
6044 return false;
6045}
6046
Eric Laurent1c333e22014-05-20 10:48:17 -07006047void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006048 struct audio_port_config *dstConfig,
6049 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006050{
Eric Laurent84c70242014-06-23 08:46:27 -07006051 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
6052
Eric Laurent1f2f2232014-06-02 12:01:23 -07006053 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6054 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6055 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006056 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006057 }
6058 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6059
Eric Laurent6a94d692014-05-20 11:18:06 -07006060 dstConfig->id = mId;
6061 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
6062 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07006063 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6064 dstConfig->ext.mix.handle = mIoHandle;
6065 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07006066}
6067
6068void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
6069 struct audio_port *port) const
6070{
Eric Laurent84c70242014-06-23 08:46:27 -07006071 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07006072 mProfile->toAudioPort(port);
6073 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006074 toAudioPortConfig(&port->active_config);
6075 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006076 port->ext.mix.handle = mIoHandle;
6077 port->ext.mix.latency_class =
6078 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
6079}
Eric Laurente552edb2014-03-10 17:42:56 -07006080
Eric Laurente0720872014-03-11 09:30:41 -07006081status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006082{
6083 const size_t SIZE = 256;
6084 char buffer[SIZE];
6085 String8 result;
6086
Eric Laurent4d416952014-08-10 14:07:09 -07006087 snprintf(buffer, SIZE, " ID: %d\n", mId);
6088 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006089 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6090 result.append(buffer);
6091 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
6092 result.append(buffer);
6093 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6094 result.append(buffer);
6095 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
6096 result.append(buffer);
6097 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
6098 result.append(buffer);
6099 snprintf(buffer, SIZE, " Devices %08x\n", device());
6100 result.append(buffer);
6101 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
6102 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07006103 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
6104 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
6105 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07006106 result.append(buffer);
6107 }
6108 write(fd, result.string(), result.size());
6109
6110 return NO_ERROR;
6111}
6112
6113// --- AudioInputDescriptor class implementation
6114
Eric Laurent1c333e22014-05-20 10:48:17 -07006115AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006116 : mId(0), mIoHandle(0),
Eric Laurentc722f302014-12-10 11:21:49 -08006117 mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006118 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07006119{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006120 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006121 mSamplingRate = profile->pickSamplingRate();
6122 mFormat = profile->pickFormat();
6123 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07006124 if (profile->mGains.size() > 0) {
6125 profile->mGains[0]->getDefaultConfig(&mGain);
6126 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006127 }
Eric Laurente552edb2014-03-10 17:42:56 -07006128}
6129
Eric Laurent1c333e22014-05-20 10:48:17 -07006130void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006131 struct audio_port_config *dstConfig,
6132 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006133{
Eric Laurent84c70242014-06-23 08:46:27 -07006134 ALOG_ASSERT(mProfile != 0,
6135 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07006136 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6137 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6138 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006139 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006140 }
6141
6142 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6143
Eric Laurent6a94d692014-05-20 11:18:06 -07006144 dstConfig->id = mId;
6145 dstConfig->role = AUDIO_PORT_ROLE_SINK;
6146 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07006147 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6148 dstConfig->ext.mix.handle = mIoHandle;
6149 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07006150}
6151
6152void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
6153 struct audio_port *port) const
6154{
Eric Laurent84c70242014-06-23 08:46:27 -07006155 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
6156
Eric Laurent1c333e22014-05-20 10:48:17 -07006157 mProfile->toAudioPort(port);
6158 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006159 toAudioPortConfig(&port->active_config);
6160 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006161 port->ext.mix.handle = mIoHandle;
6162 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
6163}
6164
Eric Laurente0720872014-03-11 09:30:41 -07006165status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006166{
6167 const size_t SIZE = 256;
6168 char buffer[SIZE];
6169 String8 result;
6170
Eric Laurent4d416952014-08-10 14:07:09 -07006171 snprintf(buffer, SIZE, " ID: %d\n", mId);
6172 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006173 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6174 result.append(buffer);
6175 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
6176 result.append(buffer);
6177 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6178 result.append(buffer);
6179 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
6180 result.append(buffer);
6181 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
6182 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07006183 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
6184 result.append(buffer);
6185
Eric Laurente552edb2014-03-10 17:42:56 -07006186 write(fd, result.string(), result.size());
6187
6188 return NO_ERROR;
6189}
6190
6191// --- StreamDescriptor class implementation
6192
Eric Laurente0720872014-03-11 09:30:41 -07006193AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07006194 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
6195{
6196 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
6197}
6198
Eric Laurente0720872014-03-11 09:30:41 -07006199int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07006200{
Eric Laurente0720872014-03-11 09:30:41 -07006201 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07006202 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
6203 if (mIndexCur.indexOfKey(device) < 0) {
6204 device = AUDIO_DEVICE_OUT_DEFAULT;
6205 }
6206 return mIndexCur.valueFor(device);
6207}
6208
Eric Laurente0720872014-03-11 09:30:41 -07006209void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006210{
6211 const size_t SIZE = 256;
6212 char buffer[SIZE];
6213 String8 result;
6214
6215 snprintf(buffer, SIZE, "%s %02d %02d ",
6216 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
6217 result.append(buffer);
6218 for (size_t i = 0; i < mIndexCur.size(); i++) {
6219 snprintf(buffer, SIZE, "%04x : %02d, ",
6220 mIndexCur.keyAt(i),
6221 mIndexCur.valueAt(i));
6222 result.append(buffer);
6223 }
6224 result.append("\n");
6225
6226 write(fd, result.string(), result.size());
6227}
6228
6229// --- EffectDescriptor class implementation
6230
Eric Laurente0720872014-03-11 09:30:41 -07006231status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006232{
6233 const size_t SIZE = 256;
6234 char buffer[SIZE];
6235 String8 result;
6236
6237 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
6238 result.append(buffer);
6239 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
6240 result.append(buffer);
6241 snprintf(buffer, SIZE, " Session: %d\n", mSession);
6242 result.append(buffer);
6243 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
6244 result.append(buffer);
6245 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
6246 result.append(buffer);
6247 write(fd, result.string(), result.size());
6248
6249 return NO_ERROR;
6250}
6251
Eric Laurent1c333e22014-05-20 10:48:17 -07006252// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006253
Eric Laurente0720872014-03-11 09:30:41 -07006254AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07006255 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
6256 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07006257{
6258}
6259
Eric Laurente0720872014-03-11 09:30:41 -07006260AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07006261{
6262 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006263 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006264 }
6265 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006266 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006267 }
6268 free((void *)mName);
6269}
6270
Eric Laurent1afeecb2014-05-14 08:52:28 -07006271status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
6272{
6273 cnode *node = root->first_child;
6274
6275 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
6276
6277 while (node) {
6278 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6279 profile->loadSamplingRates((char *)node->value);
6280 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6281 profile->loadFormats((char *)node->value);
6282 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6283 profile->loadInChannels((char *)node->value);
6284 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6285 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6286 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07006287 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
6288 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006289 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6290 profile->loadGains(node);
6291 }
6292 node = node->next;
6293 }
6294 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6295 "loadInput() invalid supported devices");
6296 ALOGW_IF(profile->mChannelMasks.size() == 0,
6297 "loadInput() invalid supported channel masks");
6298 ALOGW_IF(profile->mSamplingRates.size() == 0,
6299 "loadInput() invalid supported sampling rates");
6300 ALOGW_IF(profile->mFormats.size() == 0,
6301 "loadInput() invalid supported formats");
6302 if (!profile->mSupportedDevices.isEmpty() &&
6303 (profile->mChannelMasks.size() != 0) &&
6304 (profile->mSamplingRates.size() != 0) &&
6305 (profile->mFormats.size() != 0)) {
6306
6307 ALOGV("loadInput() adding input Supported Devices %04x",
6308 profile->mSupportedDevices.types());
6309
6310 mInputProfiles.add(profile);
6311 return NO_ERROR;
6312 } else {
6313 return BAD_VALUE;
6314 }
6315}
6316
6317status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
6318{
6319 cnode *node = root->first_child;
6320
6321 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
6322
6323 while (node) {
6324 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6325 profile->loadSamplingRates((char *)node->value);
6326 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6327 profile->loadFormats((char *)node->value);
6328 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6329 profile->loadOutChannels((char *)node->value);
6330 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6331 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6332 mDeclaredDevices);
6333 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07006334 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006335 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6336 profile->loadGains(node);
6337 }
6338 node = node->next;
6339 }
6340 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6341 "loadOutput() invalid supported devices");
6342 ALOGW_IF(profile->mChannelMasks.size() == 0,
6343 "loadOutput() invalid supported channel masks");
6344 ALOGW_IF(profile->mSamplingRates.size() == 0,
6345 "loadOutput() invalid supported sampling rates");
6346 ALOGW_IF(profile->mFormats.size() == 0,
6347 "loadOutput() invalid supported formats");
6348 if (!profile->mSupportedDevices.isEmpty() &&
6349 (profile->mChannelMasks.size() != 0) &&
6350 (profile->mSamplingRates.size() != 0) &&
6351 (profile->mFormats.size() != 0)) {
6352
6353 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
6354 profile->mSupportedDevices.types(), profile->mFlags);
6355
6356 mOutputProfiles.add(profile);
6357 return NO_ERROR;
6358 } else {
6359 return BAD_VALUE;
6360 }
6361}
6362
6363status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
6364{
6365 cnode *node = root->first_child;
6366
6367 audio_devices_t type = AUDIO_DEVICE_NONE;
6368 while (node) {
6369 if (strcmp(node->name, DEVICE_TYPE) == 0) {
6370 type = parseDeviceNames((char *)node->value);
6371 break;
6372 }
6373 node = node->next;
6374 }
6375 if (type == AUDIO_DEVICE_NONE ||
6376 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
6377 ALOGW("loadDevice() bad type %08x", type);
6378 return BAD_VALUE;
6379 }
6380 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
6381 deviceDesc->mModule = this;
6382
6383 node = root->first_child;
6384 while (node) {
6385 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
6386 deviceDesc->mAddress = String8((char *)node->value);
6387 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6388 if (audio_is_input_device(type)) {
6389 deviceDesc->loadInChannels((char *)node->value);
6390 } else {
6391 deviceDesc->loadOutChannels((char *)node->value);
6392 }
6393 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6394 deviceDesc->loadGains(node);
6395 }
6396 node = node->next;
6397 }
6398
6399 ALOGV("loadDevice() adding device name %s type %08x address %s",
6400 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6401
6402 mDeclaredDevices.add(deviceDesc);
6403
6404 return NO_ERROR;
6405}
6406
Eric Laurent275e8e92014-11-30 15:14:47 -08006407status_t AudioPolicyManager::HwModule::addOutputProfile(String8 name, const audio_config_t *config,
6408 audio_devices_t device, String8 address)
6409{
6410 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SOURCE, this);
6411
6412 profile->mSamplingRates.add(config->sample_rate);
6413 profile->mChannelMasks.add(config->channel_mask);
6414 profile->mFormats.add(config->format);
6415
Paul McLeane743a472015-01-28 11:07:31 -08006416 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(name, device);
Eric Laurent275e8e92014-11-30 15:14:47 -08006417 devDesc->mAddress = address;
6418 profile->mSupportedDevices.add(devDesc);
6419
6420 mOutputProfiles.add(profile);
6421
6422 return NO_ERROR;
6423}
6424
6425status_t AudioPolicyManager::HwModule::removeOutputProfile(String8 name)
6426{
6427 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
6428 if (mOutputProfiles[i]->mName == name) {
6429 mOutputProfiles.removeAt(i);
6430 break;
6431 }
6432 }
6433
6434 return NO_ERROR;
6435}
6436
6437status_t AudioPolicyManager::HwModule::addInputProfile(String8 name, const audio_config_t *config,
6438 audio_devices_t device, String8 address)
6439{
6440 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SINK, this);
6441
6442 profile->mSamplingRates.add(config->sample_rate);
6443 profile->mChannelMasks.add(config->channel_mask);
6444 profile->mFormats.add(config->format);
6445
Paul McLeane743a472015-01-28 11:07:31 -08006446 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(name, device);
Eric Laurent275e8e92014-11-30 15:14:47 -08006447 devDesc->mAddress = address;
6448 profile->mSupportedDevices.add(devDesc);
6449
6450 ALOGV("addInputProfile() name %s rate %d mask 0x08", name.string(), config->sample_rate, config->channel_mask);
6451
6452 mInputProfiles.add(profile);
6453
6454 return NO_ERROR;
6455}
6456
6457status_t AudioPolicyManager::HwModule::removeInputProfile(String8 name)
6458{
6459 for (size_t i = 0; i < mInputProfiles.size(); i++) {
6460 if (mInputProfiles[i]->mName == name) {
6461 mInputProfiles.removeAt(i);
6462 break;
6463 }
6464 }
6465
6466 return NO_ERROR;
6467}
6468
6469
Eric Laurente0720872014-03-11 09:30:41 -07006470void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006471{
6472 const size_t SIZE = 256;
6473 char buffer[SIZE];
6474 String8 result;
6475
6476 snprintf(buffer, SIZE, " - name: %s\n", mName);
6477 result.append(buffer);
6478 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6479 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006480 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6481 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006482 write(fd, result.string(), result.size());
6483 if (mOutputProfiles.size()) {
6484 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6485 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006486 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006487 write(fd, buffer, strlen(buffer));
6488 mOutputProfiles[i]->dump(fd);
6489 }
6490 }
6491 if (mInputProfiles.size()) {
6492 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6493 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006494 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006495 write(fd, buffer, strlen(buffer));
6496 mInputProfiles[i]->dump(fd);
6497 }
6498 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006499 if (mDeclaredDevices.size()) {
6500 write(fd, " - devices:\n", strlen(" - devices:\n"));
6501 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6502 mDeclaredDevices[i]->dump(fd, 4, i);
6503 }
6504 }
Eric Laurente552edb2014-03-10 17:42:56 -07006505}
6506
Eric Laurent1c333e22014-05-20 10:48:17 -07006507// --- AudioPort class implementation
6508
Eric Laurenta121f902014-06-03 13:32:54 -07006509
6510AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6511 audio_port_role_t role, const sp<HwModule>& module) :
Paul McLeane743a472015-01-28 11:07:31 -08006512 mName(name), mType(type), mRole(role), mModule(module), mFlags(0), mId(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006513{
6514 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6515 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6516}
6517
Paul McLeane743a472015-01-28 11:07:31 -08006518void AudioPolicyManager::AudioPort::attach(const sp<HwModule>& module) {
6519 mId = AudioPolicyManager::nextUniqueId();
6520 mModule = module;
6521}
6522
Eric Laurent1c333e22014-05-20 10:48:17 -07006523void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6524{
6525 port->role = mRole;
6526 port->type = mType;
Paul McLeane743a472015-01-28 11:07:31 -08006527 strlcpy(port->name, mName, AUDIO_PORT_MAX_NAME_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006528 unsigned int i;
6529 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006530 if (mSamplingRates[i] != 0) {
6531 port->sample_rates[i] = mSamplingRates[i];
6532 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006533 }
6534 port->num_sample_rates = i;
6535 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006536 if (mChannelMasks[i] != 0) {
6537 port->channel_masks[i] = mChannelMasks[i];
6538 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006539 }
6540 port->num_channel_masks = i;
6541 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006542 if (mFormats[i] != 0) {
6543 port->formats[i] = mFormats[i];
6544 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006545 }
6546 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006547
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006548 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006549
6550 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6551 port->gains[i] = mGains[i]->mGain;
6552 }
6553 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006554}
6555
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006556void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6557 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6558 const uint32_t rate = port->mSamplingRates.itemAt(k);
6559 if (rate != 0) { // skip "dynamic" rates
6560 bool hasRate = false;
6561 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6562 if (rate == mSamplingRates.itemAt(l)) {
6563 hasRate = true;
6564 break;
6565 }
6566 }
6567 if (!hasRate) { // never import a sampling rate twice
6568 mSamplingRates.add(rate);
6569 }
6570 }
6571 }
6572 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6573 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6574 if (mask != 0) { // skip "dynamic" masks
6575 bool hasMask = false;
6576 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6577 if (mask == mChannelMasks.itemAt(l)) {
6578 hasMask = true;
6579 break;
6580 }
6581 }
6582 if (!hasMask) { // never import a channel mask twice
6583 mChannelMasks.add(mask);
6584 }
6585 }
6586 }
6587 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6588 const audio_format_t format = port->mFormats.itemAt(k);
6589 if (format != 0) { // skip "dynamic" formats
6590 bool hasFormat = false;
6591 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6592 if (format == mFormats.itemAt(l)) {
6593 hasFormat = true;
6594 break;
6595 }
6596 }
6597 if (!hasFormat) { // never import a channel mask twice
6598 mFormats.add(format);
6599 }
6600 }
6601 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006602 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6603 sp<AudioGain> gain = port->mGains.itemAt(k);
6604 if (gain != 0) {
6605 bool hasGain = false;
6606 for (size_t l = 0 ; l < mGains.size() ; l++) {
6607 if (gain == mGains.itemAt(l)) {
6608 hasGain = true;
6609 break;
6610 }
6611 }
6612 if (!hasGain) { // never import a gain twice
6613 mGains.add(gain);
6614 }
6615 }
6616 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006617}
6618
6619void AudioPolicyManager::AudioPort::clearCapabilities() {
6620 mChannelMasks.clear();
6621 mFormats.clear();
6622 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006623 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006624}
Eric Laurent1c333e22014-05-20 10:48:17 -07006625
6626void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6627{
6628 char *str = strtok(name, "|");
6629
6630 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6631 // rates should be read from the output stream after it is opened for the first time
6632 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6633 mSamplingRates.add(0);
6634 return;
6635 }
6636
6637 while (str != NULL) {
6638 uint32_t rate = atoi(str);
6639 if (rate != 0) {
6640 ALOGV("loadSamplingRates() adding rate %d", rate);
6641 mSamplingRates.add(rate);
6642 }
6643 str = strtok(NULL, "|");
6644 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006645}
6646
6647void AudioPolicyManager::AudioPort::loadFormats(char *name)
6648{
6649 char *str = strtok(name, "|");
6650
6651 // by convention, "0' in the first entry in mFormats indicates the supported formats
6652 // should be read from the output stream after it is opened for the first time
6653 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6654 mFormats.add(AUDIO_FORMAT_DEFAULT);
6655 return;
6656 }
6657
6658 while (str != NULL) {
6659 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6660 ARRAY_SIZE(sFormatNameToEnumTable),
6661 str);
6662 if (format != AUDIO_FORMAT_DEFAULT) {
6663 mFormats.add(format);
6664 }
6665 str = strtok(NULL, "|");
6666 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006667}
6668
6669void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6670{
6671 const char *str = strtok(name, "|");
6672
6673 ALOGV("loadInChannels() %s", name);
6674
6675 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6676 mChannelMasks.add(0);
6677 return;
6678 }
6679
6680 while (str != NULL) {
6681 audio_channel_mask_t channelMask =
6682 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6683 ARRAY_SIZE(sInChannelsNameToEnumTable),
6684 str);
6685 if (channelMask != 0) {
6686 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6687 mChannelMasks.add(channelMask);
6688 }
6689 str = strtok(NULL, "|");
6690 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006691}
6692
6693void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6694{
6695 const char *str = strtok(name, "|");
6696
6697 ALOGV("loadOutChannels() %s", name);
6698
6699 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6700 // masks should be read from the output stream after it is opened for the first time
6701 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6702 mChannelMasks.add(0);
6703 return;
6704 }
6705
6706 while (str != NULL) {
6707 audio_channel_mask_t channelMask =
6708 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6709 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6710 str);
6711 if (channelMask != 0) {
6712 mChannelMasks.add(channelMask);
6713 }
6714 str = strtok(NULL, "|");
6715 }
6716 return;
6717}
6718
Eric Laurent1afeecb2014-05-14 08:52:28 -07006719audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6720{
6721 const char *str = strtok(name, "|");
6722
6723 ALOGV("loadGainMode() %s", name);
6724 audio_gain_mode_t mode = 0;
6725 while (str != NULL) {
6726 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6727 ARRAY_SIZE(sGainModeNameToEnumTable),
6728 str);
6729 str = strtok(NULL, "|");
6730 }
6731 return mode;
6732}
6733
Eric Laurenta121f902014-06-03 13:32:54 -07006734void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006735{
6736 cnode *node = root->first_child;
6737
Eric Laurenta121f902014-06-03 13:32:54 -07006738 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006739
6740 while (node) {
6741 if (strcmp(node->name, GAIN_MODE) == 0) {
6742 gain->mGain.mode = loadGainMode((char *)node->value);
6743 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006744 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006745 gain->mGain.channel_mask =
6746 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6747 ARRAY_SIZE(sInChannelsNameToEnumTable),
6748 (char *)node->value);
6749 } else {
6750 gain->mGain.channel_mask =
6751 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6752 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6753 (char *)node->value);
6754 }
6755 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6756 gain->mGain.min_value = atoi((char *)node->value);
6757 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6758 gain->mGain.max_value = atoi((char *)node->value);
6759 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6760 gain->mGain.default_value = atoi((char *)node->value);
6761 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6762 gain->mGain.step_value = atoi((char *)node->value);
6763 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6764 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6765 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6766 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6767 }
6768 node = node->next;
6769 }
6770
6771 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6772 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6773
6774 if (gain->mGain.mode == 0) {
6775 return;
6776 }
6777 mGains.add(gain);
6778}
6779
6780void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6781{
6782 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006783 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006784 while (node) {
6785 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006786 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006787 node = node->next;
6788 }
6789}
6790
Glenn Kastencbd48022014-07-24 13:46:44 -07006791status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006792{
Eric Laurent0daea392014-12-04 19:14:54 -08006793 if (mSamplingRates.isEmpty()) {
6794 return NO_ERROR;
6795 }
6796
Eric Laurenta121f902014-06-03 13:32:54 -07006797 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6798 if (mSamplingRates[i] == samplingRate) {
6799 return NO_ERROR;
6800 }
6801 }
6802 return BAD_VALUE;
6803}
6804
Glenn Kastencbd48022014-07-24 13:46:44 -07006805status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6806 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006807{
Eric Laurent0daea392014-12-04 19:14:54 -08006808 if (mSamplingRates.isEmpty()) {
6809 return NO_ERROR;
6810 }
6811
Glenn Kastencbd48022014-07-24 13:46:44 -07006812 // Search for the closest supported sampling rate that is above (preferred)
6813 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6814 // The sampling rates do not need to be sorted in ascending order.
6815 ssize_t maxBelow = -1;
6816 ssize_t minAbove = -1;
6817 uint32_t candidate;
6818 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6819 candidate = mSamplingRates[i];
6820 if (candidate == samplingRate) {
6821 if (updatedSamplingRate != NULL) {
6822 *updatedSamplingRate = candidate;
6823 }
6824 return NO_ERROR;
6825 }
6826 // candidate < desired
6827 if (candidate < samplingRate) {
6828 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6829 maxBelow = i;
6830 }
6831 // candidate > desired
6832 } else {
6833 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6834 minAbove = i;
6835 }
6836 }
6837 }
6838 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6839 // TODO Move these assumptions out.
6840 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6841 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6842 // due to approximation by an int32_t of the
6843 // phase increments
6844 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6845 if (minAbove >= 0) {
6846 candidate = mSamplingRates[minAbove];
6847 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6848 if (updatedSamplingRate != NULL) {
6849 *updatedSamplingRate = candidate;
6850 }
6851 return NO_ERROR;
6852 }
6853 }
6854 // But if we have to up-sample from a lower sampling rate, that's OK.
6855 if (maxBelow >= 0) {
6856 candidate = mSamplingRates[maxBelow];
6857 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6858 if (updatedSamplingRate != NULL) {
6859 *updatedSamplingRate = candidate;
6860 }
6861 return NO_ERROR;
6862 }
6863 }
6864 // leave updatedSamplingRate unmodified
6865 return BAD_VALUE;
6866}
6867
6868status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6869{
Eric Laurent0daea392014-12-04 19:14:54 -08006870 if (mChannelMasks.isEmpty()) {
6871 return NO_ERROR;
6872 }
6873
Glenn Kastencbd48022014-07-24 13:46:44 -07006874 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006875 if (mChannelMasks[i] == channelMask) {
6876 return NO_ERROR;
6877 }
6878 }
6879 return BAD_VALUE;
6880}
6881
Glenn Kastencbd48022014-07-24 13:46:44 -07006882status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6883 const
6884{
Eric Laurent0daea392014-12-04 19:14:54 -08006885 if (mChannelMasks.isEmpty()) {
6886 return NO_ERROR;
6887 }
6888
Glenn Kastencbd48022014-07-24 13:46:44 -07006889 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6890 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6891 // FIXME Does not handle multi-channel automatic conversions yet
6892 audio_channel_mask_t supported = mChannelMasks[i];
6893 if (supported == channelMask) {
6894 return NO_ERROR;
6895 }
6896 if (isRecordThread) {
6897 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6898 // FIXME Abstract this out to a table.
6899 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6900 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6901 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6902 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6903 return NO_ERROR;
6904 }
6905 }
6906 }
6907 return BAD_VALUE;
6908}
6909
Eric Laurenta121f902014-06-03 13:32:54 -07006910status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6911{
Eric Laurent0daea392014-12-04 19:14:54 -08006912 if (mFormats.isEmpty()) {
6913 return NO_ERROR;
6914 }
6915
Eric Laurenta121f902014-06-03 13:32:54 -07006916 for (size_t i = 0; i < mFormats.size(); i ++) {
6917 if (mFormats[i] == format) {
6918 return NO_ERROR;
6919 }
6920 }
6921 return BAD_VALUE;
6922}
6923
Eric Laurent1e693b52014-07-09 15:03:28 -07006924
6925uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6926{
6927 // special case for uninitialized dynamic profile
6928 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6929 return 0;
6930 }
6931
Eric Laurent828bcff2014-09-07 12:26:06 -07006932 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6933 // channel count / sampling rate combination chosen will be supported by the connected
6934 // sink
6935 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6936 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6937 uint32_t samplingRate = UINT_MAX;
6938 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6939 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6940 samplingRate = mSamplingRates[i];
6941 }
6942 }
6943 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6944 }
6945
Eric Laurent1e693b52014-07-09 15:03:28 -07006946 uint32_t samplingRate = 0;
6947 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6948
6949 // For mixed output and inputs, use max mixer sampling rates. Do not
6950 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006951 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006952 maxRate = UINT_MAX;
6953 }
6954 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6955 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6956 samplingRate = mSamplingRates[i];
6957 }
6958 }
6959 return samplingRate;
6960}
6961
6962audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6963{
6964 // special case for uninitialized dynamic profile
6965 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6966 return AUDIO_CHANNEL_NONE;
6967 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006968 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006969
6970 // For direct outputs, pick minimum channel count: this helps ensuring that the
6971 // channel count / sampling rate combination chosen will be supported by the connected
6972 // sink
6973 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6974 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6975 uint32_t channelCount = UINT_MAX;
6976 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6977 uint32_t cnlCount;
6978 if (mUseInChannelMask) {
6979 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6980 } else {
6981 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6982 }
6983 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6984 channelMask = mChannelMasks[i];
6985 channelCount = cnlCount;
6986 }
6987 }
6988 return channelMask;
6989 }
6990
Eric Laurent1e693b52014-07-09 15:03:28 -07006991 uint32_t channelCount = 0;
6992 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6993
6994 // For mixed output and inputs, use max mixer channel count. Do not
6995 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006996 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006997 maxCount = UINT_MAX;
6998 }
6999 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
7000 uint32_t cnlCount;
7001 if (mUseInChannelMask) {
7002 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
7003 } else {
7004 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
7005 }
7006 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
7007 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07007008 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07007009 }
7010 }
7011 return channelMask;
7012}
7013
Andy Hung9a605382014-07-28 16:16:31 -07007014/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07007015const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
7016 AUDIO_FORMAT_DEFAULT,
7017 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07007018 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07007019 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07007020 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07007021 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07007022};
7023
7024int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
7025 audio_format_t format2)
7026{
7027 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
7028 // compressed format and better than any PCM format. This is by design of pickFormat()
7029 if (!audio_is_linear_pcm(format1)) {
7030 if (!audio_is_linear_pcm(format2)) {
7031 return 0;
7032 }
7033 return 1;
7034 }
7035 if (!audio_is_linear_pcm(format2)) {
7036 return -1;
7037 }
7038
7039 int index1 = -1, index2 = -1;
7040 for (size_t i = 0;
7041 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
7042 i ++) {
7043 if (sPcmFormatCompareTable[i] == format1) {
7044 index1 = i;
7045 }
7046 if (sPcmFormatCompareTable[i] == format2) {
7047 index2 = i;
7048 }
7049 }
7050 // format1 not found => index1 < 0 => format2 > format1
7051 // format2 not found => index2 < 0 => format2 < format1
7052 return index1 - index2;
7053}
7054
7055audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
7056{
7057 // special case for uninitialized dynamic profile
7058 if (mFormats.size() == 1 && mFormats[0] == 0) {
7059 return AUDIO_FORMAT_DEFAULT;
7060 }
7061
7062 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07007063 audio_format_t bestFormat =
7064 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
7065 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07007066 // For mixed output and inputs, use best mixer output format. Do not
7067 // limit format otherwise
7068 if ((mType != AUDIO_PORT_TYPE_MIX) ||
7069 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07007070 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007071 bestFormat = AUDIO_FORMAT_INVALID;
7072 }
7073
7074 for (size_t i = 0; i < mFormats.size(); i ++) {
7075 if ((compareFormats(mFormats[i], format) > 0) &&
7076 (compareFormats(mFormats[i], bestFormat) <= 0)) {
7077 format = mFormats[i];
7078 }
7079 }
7080 return format;
7081}
7082
Eric Laurenta121f902014-06-03 13:32:54 -07007083status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
7084 int index) const
7085{
7086 if (index < 0 || (size_t)index >= mGains.size()) {
7087 return BAD_VALUE;
7088 }
7089 return mGains[index]->checkConfig(gainConfig);
7090}
7091
Eric Laurent1afeecb2014-05-14 08:52:28 -07007092void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
7093{
7094 const size_t SIZE = 256;
7095 char buffer[SIZE];
7096 String8 result;
7097
7098 if (mName.size() != 0) {
7099 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
7100 result.append(buffer);
7101 }
7102
7103 if (mSamplingRates.size() != 0) {
7104 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
7105 result.append(buffer);
7106 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007107 if (i == 0 && mSamplingRates[i] == 0) {
7108 snprintf(buffer, SIZE, "Dynamic");
7109 } else {
7110 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
7111 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007112 result.append(buffer);
7113 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
7114 }
7115 result.append("\n");
7116 }
7117
7118 if (mChannelMasks.size() != 0) {
7119 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
7120 result.append(buffer);
7121 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007122 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
7123
7124 if (i == 0 && mChannelMasks[i] == 0) {
7125 snprintf(buffer, SIZE, "Dynamic");
7126 } else {
7127 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
7128 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007129 result.append(buffer);
7130 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
7131 }
7132 result.append("\n");
7133 }
7134
7135 if (mFormats.size() != 0) {
7136 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
7137 result.append(buffer);
7138 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007139 const char *formatStr = enumToString(sFormatNameToEnumTable,
7140 ARRAY_SIZE(sFormatNameToEnumTable),
7141 mFormats[i]);
7142 if (i == 0 && strcmp(formatStr, "") == 0) {
7143 snprintf(buffer, SIZE, "Dynamic");
7144 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07007145 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07007146 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007147 result.append(buffer);
7148 result.append(i == (mFormats.size() - 1) ? "" : ", ");
7149 }
7150 result.append("\n");
7151 }
7152 write(fd, result.string(), result.size());
7153 if (mGains.size() != 0) {
7154 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
7155 write(fd, buffer, strlen(buffer) + 1);
7156 result.append(buffer);
7157 for (size_t i = 0; i < mGains.size(); i++) {
7158 mGains[i]->dump(fd, spaces + 2, i);
7159 }
7160 }
7161}
7162
7163// --- AudioGain class implementation
7164
Eric Laurenta121f902014-06-03 13:32:54 -07007165AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07007166{
Eric Laurenta121f902014-06-03 13:32:54 -07007167 mIndex = index;
7168 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007169 memset(&mGain, 0, sizeof(struct audio_gain));
7170}
7171
Eric Laurenta121f902014-06-03 13:32:54 -07007172void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
7173{
7174 config->index = mIndex;
7175 config->mode = mGain.mode;
7176 config->channel_mask = mGain.channel_mask;
7177 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7178 config->values[0] = mGain.default_value;
7179 } else {
7180 uint32_t numValues;
7181 if (mUseInChannelMask) {
7182 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
7183 } else {
7184 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
7185 }
7186 for (size_t i = 0; i < numValues; i++) {
7187 config->values[i] = mGain.default_value;
7188 }
7189 }
7190 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7191 config->ramp_duration_ms = mGain.min_ramp_ms;
7192 }
7193}
7194
7195status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
7196{
7197 if ((config->mode & ~mGain.mode) != 0) {
7198 return BAD_VALUE;
7199 }
7200 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7201 if ((config->values[0] < mGain.min_value) ||
7202 (config->values[0] > mGain.max_value)) {
7203 return BAD_VALUE;
7204 }
7205 } else {
7206 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
7207 return BAD_VALUE;
7208 }
7209 uint32_t numValues;
7210 if (mUseInChannelMask) {
7211 numValues = audio_channel_count_from_in_mask(config->channel_mask);
7212 } else {
7213 numValues = audio_channel_count_from_out_mask(config->channel_mask);
7214 }
7215 for (size_t i = 0; i < numValues; i++) {
7216 if ((config->values[i] < mGain.min_value) ||
7217 (config->values[i] > mGain.max_value)) {
7218 return BAD_VALUE;
7219 }
7220 }
7221 }
7222 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7223 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
7224 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
7225 return BAD_VALUE;
7226 }
7227 }
7228 return NO_ERROR;
7229}
7230
Eric Laurent1afeecb2014-05-14 08:52:28 -07007231void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
7232{
7233 const size_t SIZE = 256;
7234 char buffer[SIZE];
7235 String8 result;
7236
7237 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
7238 result.append(buffer);
7239 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
7240 result.append(buffer);
7241 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
7242 result.append(buffer);
7243 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
7244 result.append(buffer);
7245 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
7246 result.append(buffer);
7247 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
7248 result.append(buffer);
7249 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
7250 result.append(buffer);
7251 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
7252 result.append(buffer);
7253 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
7254 result.append(buffer);
7255
7256 write(fd, result.string(), result.size());
7257}
7258
Eric Laurent1f2f2232014-06-02 12:01:23 -07007259// --- AudioPortConfig class implementation
7260
7261AudioPolicyManager::AudioPortConfig::AudioPortConfig()
7262{
7263 mSamplingRate = 0;
7264 mChannelMask = AUDIO_CHANNEL_NONE;
7265 mFormat = AUDIO_FORMAT_INVALID;
7266 mGain.index = -1;
7267}
7268
Eric Laurenta121f902014-06-03 13:32:54 -07007269status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
7270 const struct audio_port_config *config,
7271 struct audio_port_config *backupConfig)
7272{
7273 struct audio_port_config localBackupConfig;
7274 status_t status = NO_ERROR;
7275
7276 localBackupConfig.config_mask = config->config_mask;
7277 toAudioPortConfig(&localBackupConfig);
7278
Marco Nelissen961ec212014-08-25 15:58:39 -07007279 sp<AudioPort> audioport = getAudioPort();
7280 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07007281 status = NO_INIT;
7282 goto exit;
7283 }
7284 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007285 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07007286 if (status != NO_ERROR) {
7287 goto exit;
7288 }
7289 mSamplingRate = config->sample_rate;
7290 }
7291 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007292 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07007293 if (status != NO_ERROR) {
7294 goto exit;
7295 }
7296 mChannelMask = config->channel_mask;
7297 }
7298 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007299 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07007300 if (status != NO_ERROR) {
7301 goto exit;
7302 }
7303 mFormat = config->format;
7304 }
7305 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007306 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07007307 if (status != NO_ERROR) {
7308 goto exit;
7309 }
7310 mGain = config->gain;
7311 }
7312
7313exit:
7314 if (status != NO_ERROR) {
7315 applyAudioPortConfig(&localBackupConfig);
7316 }
7317 if (backupConfig != NULL) {
7318 *backupConfig = localBackupConfig;
7319 }
7320 return status;
7321}
7322
Eric Laurent1f2f2232014-06-02 12:01:23 -07007323void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
7324 struct audio_port_config *dstConfig,
7325 const struct audio_port_config *srcConfig) const
7326{
7327 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
7328 dstConfig->sample_rate = mSamplingRate;
7329 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
7330 dstConfig->sample_rate = srcConfig->sample_rate;
7331 }
7332 } else {
7333 dstConfig->sample_rate = 0;
7334 }
7335 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
7336 dstConfig->channel_mask = mChannelMask;
7337 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
7338 dstConfig->channel_mask = srcConfig->channel_mask;
7339 }
7340 } else {
7341 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
7342 }
7343 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
7344 dstConfig->format = mFormat;
7345 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
7346 dstConfig->format = srcConfig->format;
7347 }
7348 } else {
7349 dstConfig->format = AUDIO_FORMAT_INVALID;
7350 }
7351 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
7352 dstConfig->gain = mGain;
7353 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
7354 dstConfig->gain = srcConfig->gain;
7355 }
7356 } else {
7357 dstConfig->gain.index = -1;
7358 }
7359 if (dstConfig->gain.index != -1) {
7360 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
7361 } else {
7362 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
7363 }
7364}
7365
Eric Laurent1c333e22014-05-20 10:48:17 -07007366// --- IOProfile class implementation
7367
Eric Laurent1afeecb2014-05-14 08:52:28 -07007368AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07007369 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07007370 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07007371{
7372}
7373
Eric Laurente0720872014-03-11 09:30:41 -07007374AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07007375{
7376}
7377
7378// checks if the IO profile is compatible with specified parameters.
7379// Sampling rate, format and channel mask must be specified in order to
7380// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07007381bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08007382 String8 address,
7383 uint32_t samplingRate,
7384 uint32_t *updatedSamplingRate,
7385 audio_format_t format,
7386 audio_channel_mask_t channelMask,
7387 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07007388{
Glenn Kastencbd48022014-07-24 13:46:44 -07007389 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
7390 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
7391 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07007392
Eric Laurent275e8e92014-11-30 15:14:47 -08007393 if (device != AUDIO_DEVICE_NONE && mSupportedDevices.getDevice(device, address) == 0) {
Glenn Kastencbd48022014-07-24 13:46:44 -07007394 return false;
7395 }
7396
7397 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07007398 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007399 }
7400 uint32_t myUpdatedSamplingRate = samplingRate;
7401 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007402 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007403 }
7404 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
7405 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007406 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007407 }
7408
7409 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
7410 return false;
7411 }
7412
7413 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
7414 checkExactChannelMask(channelMask) != NO_ERROR)) {
7415 return false;
7416 }
7417 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
7418 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
7419 return false;
7420 }
7421
7422 if (isPlaybackThread && (mFlags & flags) != flags) {
7423 return false;
7424 }
7425 // The only input flag that is allowed to be different is the fast flag.
7426 // An existing fast stream is compatible with a normal track request.
7427 // An existing normal stream is compatible with a fast track request,
7428 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07007429 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07007430 ~AUDIO_INPUT_FLAG_FAST)) {
7431 return false;
7432 }
7433
7434 if (updatedSamplingRate != NULL) {
7435 *updatedSamplingRate = myUpdatedSamplingRate;
7436 }
7437 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07007438}
7439
Eric Laurente0720872014-03-11 09:30:41 -07007440void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07007441{
7442 const size_t SIZE = 256;
7443 char buffer[SIZE];
7444 String8 result;
7445
Eric Laurent1afeecb2014-05-14 08:52:28 -07007446 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007447
Eric Laurente552edb2014-03-10 17:42:56 -07007448 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
7449 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007450 snprintf(buffer, SIZE, " - devices:\n");
7451 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07007452 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07007453 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
7454 mSupportedDevices[i]->dump(fd, 6, i);
7455 }
Eric Laurente552edb2014-03-10 17:42:56 -07007456}
7457
Eric Laurentd4692962014-05-05 18:13:44 -07007458void AudioPolicyManager::IOProfile::log()
7459{
7460 const size_t SIZE = 256;
7461 char buffer[SIZE];
7462 String8 result;
7463
7464 ALOGV(" - sampling rates: ");
7465 for (size_t i = 0; i < mSamplingRates.size(); i++) {
7466 ALOGV(" %d", mSamplingRates[i]);
7467 }
7468
7469 ALOGV(" - channel masks: ");
7470 for (size_t i = 0; i < mChannelMasks.size(); i++) {
7471 ALOGV(" 0x%04x", mChannelMasks[i]);
7472 }
7473
7474 ALOGV(" - formats: ");
7475 for (size_t i = 0; i < mFormats.size(); i++) {
7476 ALOGV(" 0x%08x", mFormats[i]);
7477 }
7478
7479 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
7480 ALOGV(" - flags: 0x%04x\n", mFlags);
7481}
7482
7483
Eric Laurent3a4311c2014-03-17 12:00:47 -07007484// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07007485
Paul McLeane743a472015-01-28 11:07:31 -08007486String8 AudioPolicyManager::DeviceDescriptor::emptyNameStr = String8("");
Eric Laurent1f2f2232014-06-02 12:01:23 -07007487
7488AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
7489 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7490 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7491 AUDIO_PORT_ROLE_SOURCE,
7492 NULL),
Paul McLeane743a472015-01-28 11:07:31 -08007493 mDeviceType(type), mAddress("")
Eric Laurent1f2f2232014-06-02 12:01:23 -07007494{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007495}
7496
Eric Laurent3a4311c2014-03-17 12:00:47 -07007497bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07007498{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007499 // Devices are considered equal if they:
7500 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7501 // - have the same address or one device does not specify the address
7502 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007503 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007504 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007505 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007506 mChannelMask == other->mChannelMask);
7507}
7508
Eric Laurent1db89b92015-01-27 18:21:09 -08007509void AudioPolicyManager::DeviceDescriptor::loadGains(cnode *root)
7510{
7511 AudioPort::loadGains(root);
7512 if (mGains.size() > 0) {
7513 mGains[0]->getDefaultConfig(&mGain);
7514 }
7515}
7516
7517
Eric Laurent3a4311c2014-03-17 12:00:47 -07007518void AudioPolicyManager::DeviceVector::refreshTypes()
7519{
Eric Laurent1c333e22014-05-20 10:48:17 -07007520 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007521 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007522 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007523 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007524 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007525}
7526
7527ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7528{
7529 for(size_t i = 0; i < size(); i++) {
7530 if (item->equals(itemAt(i))) {
7531 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007532 }
7533 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007534 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007535}
7536
Eric Laurent3a4311c2014-03-17 12:00:47 -07007537ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007538{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007539 ssize_t ret = indexOf(item);
7540
7541 if (ret < 0) {
7542 ret = SortedVector::add(item);
7543 if (ret >= 0) {
7544 refreshTypes();
7545 }
7546 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007547 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007548 ret = -1;
7549 }
7550 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007551}
7552
Eric Laurent3a4311c2014-03-17 12:00:47 -07007553ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7554{
7555 size_t i;
7556 ssize_t ret = indexOf(item);
7557
7558 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007559 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007560 } else {
7561 ret = SortedVector::removeAt(ret);
7562 if (ret >= 0) {
7563 refreshTypes();
7564 }
7565 }
7566 return ret;
7567}
7568
7569void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7570{
7571 DeviceVector deviceList;
7572
7573 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7574 types &= ~role_bit;
7575
7576 while (types) {
7577 uint32_t i = 31 - __builtin_clz(types);
7578 uint32_t type = 1 << i;
7579 types &= ~type;
Paul McLeane743a472015-01-28 11:07:31 -08007580 add(new DeviceDescriptor(String8("device_type"), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007581 }
7582}
7583
Eric Laurent1afeecb2014-05-14 08:52:28 -07007584void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7585 const DeviceVector& declaredDevices)
7586{
7587 char *devName = strtok(name, "|");
7588 while (devName != NULL) {
7589 if (strlen(devName) != 0) {
7590 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7591 ARRAY_SIZE(sDeviceNameToEnumTable),
7592 devName);
7593 if (type != AUDIO_DEVICE_NONE) {
Paul McLeane743a472015-01-28 11:07:31 -08007594 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(name), type);
Eric Laurent275e8e92014-11-30 15:14:47 -08007595 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX ||
7596 type == AUDIO_DEVICE_OUT_REMOTE_SUBMIX ) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007597 dev->mAddress = String8("0");
7598 }
7599 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007600 } else {
7601 sp<DeviceDescriptor> deviceDesc =
7602 declaredDevices.getDeviceFromName(String8(devName));
7603 if (deviceDesc != 0) {
7604 add(deviceDesc);
7605 }
7606 }
7607 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007608 devName = strtok(NULL, "|");
Eric Laurent1afeecb2014-05-14 08:52:28 -07007609 }
7610}
7611
Eric Laurent1c333e22014-05-20 10:48:17 -07007612sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7613 audio_devices_t type, String8 address) const
7614{
7615 sp<DeviceDescriptor> device;
7616 for (size_t i = 0; i < size(); i++) {
7617 if (itemAt(i)->mDeviceType == type) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007618 if (address == "" || itemAt(i)->mAddress == address) {
7619 device = itemAt(i);
7620 if (itemAt(i)->mAddress == address) {
7621 break;
7622 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007623 }
7624 }
7625 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007626 ALOGV("DeviceVector::getDevice() for type %08x address %s found %p",
Eric Laurent1c333e22014-05-20 10:48:17 -07007627 type, address.string(), device.get());
7628 return device;
7629}
7630
Eric Laurent6a94d692014-05-20 11:18:06 -07007631sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7632 audio_port_handle_t id) const
7633{
7634 sp<DeviceDescriptor> device;
7635 for (size_t i = 0; i < size(); i++) {
Paul McLeane743a472015-01-28 11:07:31 -08007636 if (itemAt(i)->getHandle() == id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07007637 device = itemAt(i);
7638 break;
7639 }
7640 }
7641 return device;
7642}
7643
Eric Laurent1c333e22014-05-20 10:48:17 -07007644AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7645 audio_devices_t type) const
7646{
7647 DeviceVector devices;
7648 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7649 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7650 devices.add(itemAt(i));
7651 type &= ~itemAt(i)->mDeviceType;
7652 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7653 itemAt(i)->mDeviceType, itemAt(i).get());
7654 }
7655 }
7656 return devices;
7657}
7658
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007659AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7660 audio_devices_t type, String8 address) const
7661{
7662 DeviceVector devices;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007663 for (size_t i = 0; i < size(); i++) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007664 if (itemAt(i)->mDeviceType == type) {
7665 if (itemAt(i)->mAddress == address) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007666 devices.add(itemAt(i));
7667 }
7668 }
7669 }
7670 return devices;
7671}
7672
Eric Laurent1afeecb2014-05-14 08:52:28 -07007673sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7674 const String8& name) const
7675{
7676 sp<DeviceDescriptor> device;
7677 for (size_t i = 0; i < size(); i++) {
7678 if (itemAt(i)->mName == name) {
7679 device = itemAt(i);
7680 break;
7681 }
7682 }
7683 return device;
7684}
7685
Eric Laurent6a94d692014-05-20 11:18:06 -07007686void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7687 struct audio_port_config *dstConfig,
7688 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007689{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007690 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7691 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007692 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007693 }
7694
7695 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07007696 dstConfig->id = mId;
7697 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007698 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007699 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007700 dstConfig->ext.device.type = mDeviceType;
Paul McLeane743a472015-01-28 11:07:31 -08007701
7702 //TODO Understand why this test is necessary. i.e. why at boot time does it crash
7703 // without the test?
7704 // This has been demonstrated to NOT be true (at start up)
7705 // ALOG_ASSERT(mModule != NULL);
7706 dstConfig->ext.device.hw_module = mModule != NULL ? mModule->mHandle : NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07007707 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007708}
7709
7710void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7711{
Eric Laurent83b88082014-06-20 18:31:16 -07007712 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007713 AudioPort::toAudioPort(port);
7714 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007715 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007716 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007717 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007718 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7719}
7720
Eric Laurent1afeecb2014-05-14 08:52:28 -07007721status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007722{
7723 const size_t SIZE = 256;
7724 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007725 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007726
Eric Laurent1afeecb2014-05-14 08:52:28 -07007727 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7728 result.append(buffer);
7729 if (mId != 0) {
7730 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7731 result.append(buffer);
7732 }
7733 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7734 enumToString(sDeviceNameToEnumTable,
7735 ARRAY_SIZE(sDeviceNameToEnumTable),
7736 mDeviceType));
7737 result.append(buffer);
7738 if (mAddress.size() != 0) {
7739 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7740 result.append(buffer);
7741 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007742 write(fd, result.string(), result.size());
7743 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007744
7745 return NO_ERROR;
7746}
7747
Eric Laurent4d416952014-08-10 14:07:09 -07007748status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7749{
7750 const size_t SIZE = 256;
7751 char buffer[SIZE];
7752 String8 result;
7753
7754
7755 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7756 result.append(buffer);
7757 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7758 result.append(buffer);
7759 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7760 result.append(buffer);
7761 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7762 result.append(buffer);
7763 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7764 result.append(buffer);
7765 for (size_t i = 0; i < mPatch.num_sources; i++) {
7766 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7767 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7768 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7769 ARRAY_SIZE(sDeviceNameToEnumTable),
7770 mPatch.sources[i].ext.device.type));
7771 } else {
7772 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7773 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7774 }
7775 result.append(buffer);
7776 }
7777 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7778 result.append(buffer);
7779 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7780 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7781 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7782 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7783 ARRAY_SIZE(sDeviceNameToEnumTable),
7784 mPatch.sinks[i].ext.device.type));
7785 } else {
7786 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7787 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7788 }
7789 result.append(buffer);
7790 }
7791
7792 write(fd, result.string(), result.size());
7793 return NO_ERROR;
7794}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007795
7796// --- audio_policy.conf file parsing
7797
Eric Laurent5dbe4712014-09-19 19:04:57 -07007798uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007799{
7800 uint32_t flag = 0;
7801
7802 // it is OK to cast name to non const here as we are not going to use it after
7803 // strtok() modifies it
7804 char *flagName = strtok(name, "|");
7805 while (flagName != NULL) {
7806 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007807 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7808 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007809 flagName);
7810 }
7811 flagName = strtok(NULL, "|");
7812 }
7813 //force direct flag if offload flag is set: offloading implies a direct output stream
7814 // and all common behaviors are driven by checking only the direct flag
7815 // this should normally be set appropriately in the policy configuration file
7816 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7817 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7818 }
7819
Eric Laurent5dbe4712014-09-19 19:04:57 -07007820 return flag;
7821}
7822
7823uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7824{
7825 uint32_t flag = 0;
7826
7827 // it is OK to cast name to non const here as we are not going to use it after
7828 // strtok() modifies it
7829 char *flagName = strtok(name, "|");
7830 while (flagName != NULL) {
7831 if (strlen(flagName) != 0) {
7832 flag |= stringToEnum(sInputFlagNameToEnumTable,
7833 ARRAY_SIZE(sInputFlagNameToEnumTable),
7834 flagName);
7835 }
7836 flagName = strtok(NULL, "|");
7837 }
7838 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007839}
7840
Eric Laurente0720872014-03-11 09:30:41 -07007841audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007842{
7843 uint32_t device = 0;
7844
7845 char *devName = strtok(name, "|");
7846 while (devName != NULL) {
7847 if (strlen(devName) != 0) {
7848 device |= stringToEnum(sDeviceNameToEnumTable,
7849 ARRAY_SIZE(sDeviceNameToEnumTable),
7850 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007851 }
Eric Laurente552edb2014-03-10 17:42:56 -07007852 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007853 }
Eric Laurente552edb2014-03-10 17:42:56 -07007854 return device;
7855}
7856
Eric Laurente0720872014-03-11 09:30:41 -07007857void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007858{
Eric Laurente552edb2014-03-10 17:42:56 -07007859 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007860 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007861 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007862
Eric Laurent1afeecb2014-05-14 08:52:28 -07007863 node = config_find(root, DEVICES_TAG);
7864 if (node != NULL) {
7865 node = node->first_child;
7866 while (node) {
7867 ALOGV("loadHwModule() loading device %s", node->name);
7868 status_t tmpStatus = module->loadDevice(node);
7869 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7870 status = tmpStatus;
7871 }
7872 node = node->next;
7873 }
7874 }
7875 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007876 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007877 node = node->first_child;
7878 while (node) {
7879 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007880 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007881 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7882 status = tmpStatus;
7883 }
7884 node = node->next;
7885 }
7886 }
7887 node = config_find(root, INPUTS_TAG);
7888 if (node != NULL) {
7889 node = node->first_child;
7890 while (node) {
7891 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007892 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007893 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7894 status = tmpStatus;
7895 }
7896 node = node->next;
7897 }
7898 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007899 loadGlobalConfig(root, module);
7900
Eric Laurente552edb2014-03-10 17:42:56 -07007901 if (status == NO_ERROR) {
7902 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007903 }
7904}
7905
Eric Laurente0720872014-03-11 09:30:41 -07007906void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007907{
7908 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7909 if (node == NULL) {
7910 return;
7911 }
7912
7913 node = node->first_child;
7914 while (node) {
7915 ALOGV("loadHwModules() loading module %s", node->name);
7916 loadHwModule(node);
7917 node = node->next;
7918 }
7919}
7920
Eric Laurent1f2f2232014-06-02 12:01:23 -07007921void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007922{
7923 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007924
Eric Laurente552edb2014-03-10 17:42:56 -07007925 if (node == NULL) {
7926 return;
7927 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007928 DeviceVector declaredDevices;
7929 if (module != NULL) {
7930 declaredDevices = module->mDeclaredDevices;
7931 }
7932
Eric Laurente552edb2014-03-10 17:42:56 -07007933 node = node->first_child;
7934 while (node) {
7935 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007936 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7937 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007938 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7939 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007940 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007941 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007942 ARRAY_SIZE(sDeviceNameToEnumTable),
7943 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007944 if (device != AUDIO_DEVICE_NONE) {
Paul McLeane743a472015-01-28 11:07:31 -08007945 mDefaultOutputDevice = new DeviceDescriptor(String8("default-output"), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007946 } else {
7947 ALOGW("loadGlobalConfig() default device not specified");
7948 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007949 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007950 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007951 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7952 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007953 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007954 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7955 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7956 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007957 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7958 uint32_t major, minor;
7959 sscanf((char *)node->value, "%u.%u", &major, &minor);
7960 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7961 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7962 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007963 }
7964 node = node->next;
7965 }
7966}
7967
Eric Laurente0720872014-03-11 09:30:41 -07007968status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007969{
7970 cnode *root;
7971 char *data;
7972
7973 data = (char *)load_file(path, NULL);
7974 if (data == NULL) {
7975 return -ENODEV;
7976 }
7977 root = config_node("", "");
7978 config_load(root, data);
7979
Eric Laurente552edb2014-03-10 17:42:56 -07007980 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007981 // legacy audio_policy.conf files have one global_configuration section
7982 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007983 config_free(root);
7984 free(root);
7985 free(data);
7986
7987 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7988
7989 return NO_ERROR;
7990}
7991
Eric Laurente0720872014-03-11 09:30:41 -07007992void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007993{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007994 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007995 sp<IOProfile> profile;
Paul McLeane743a472015-01-28 11:07:31 -08007996 sp<DeviceDescriptor> defaultInputDevice =
7997 new DeviceDescriptor(String8("builtin-mic"), AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007998 mAvailableOutputDevices.add(mDefaultOutputDevice);
7999 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07008000
8001 module = new HwModule("primary");
8002
Eric Laurent1afeecb2014-05-14 08:52:28 -07008003 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07008004 profile->mSamplingRates.add(44100);
8005 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
8006 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07008007 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07008008 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
8009 module->mOutputProfiles.add(profile);
8010
Eric Laurent1afeecb2014-05-14 08:52:28 -07008011 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07008012 profile->mSamplingRates.add(8000);
8013 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
8014 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07008015 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07008016 module->mInputProfiles.add(profile);
8017
8018 mHwModules.add(module);
8019}
8020
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07008021audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
8022{
8023 // flags to stream type mapping
8024 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
8025 return AUDIO_STREAM_ENFORCED_AUDIBLE;
8026 }
8027 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
8028 return AUDIO_STREAM_BLUETOOTH_SCO;
8029 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08008030 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
8031 return AUDIO_STREAM_TTS;
8032 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07008033
8034 // usage to stream type mapping
8035 switch (attr->usage) {
8036 case AUDIO_USAGE_MEDIA:
8037 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07008038 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8039 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08008040 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08008041 if (isStreamActive(AUDIO_STREAM_ALARM)) {
8042 return AUDIO_STREAM_ALARM;
8043 }
8044 if (isStreamActive(AUDIO_STREAM_RING)) {
8045 return AUDIO_STREAM_RING;
8046 }
8047 if (isInCall()) {
8048 return AUDIO_STREAM_VOICE_CALL;
8049 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08008050 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07008051 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8052 return AUDIO_STREAM_SYSTEM;
8053 case AUDIO_USAGE_VOICE_COMMUNICATION:
8054 return AUDIO_STREAM_VOICE_CALL;
8055
8056 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8057 return AUDIO_STREAM_DTMF;
8058
8059 case AUDIO_USAGE_ALARM:
8060 return AUDIO_STREAM_ALARM;
8061 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8062 return AUDIO_STREAM_RING;
8063
8064 case AUDIO_USAGE_NOTIFICATION:
8065 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8066 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8067 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8068 case AUDIO_USAGE_NOTIFICATION_EVENT:
8069 return AUDIO_STREAM_NOTIFICATION;
8070
8071 case AUDIO_USAGE_UNKNOWN:
8072 default:
8073 return AUDIO_STREAM_MUSIC;
8074 }
8075}
Eric Laurente83b55d2014-11-14 10:06:21 -08008076
8077bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
8078 // has flags that map to a strategy?
8079 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8080 return true;
8081 }
8082
8083 // has known usage?
8084 switch (paa->usage) {
8085 case AUDIO_USAGE_UNKNOWN:
8086 case AUDIO_USAGE_MEDIA:
8087 case AUDIO_USAGE_VOICE_COMMUNICATION:
8088 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8089 case AUDIO_USAGE_ALARM:
8090 case AUDIO_USAGE_NOTIFICATION:
8091 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8092 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8093 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8094 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8095 case AUDIO_USAGE_NOTIFICATION_EVENT:
8096 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8097 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8098 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8099 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008100 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08008101 break;
8102 default:
8103 return false;
8104 }
8105 return true;
8106}
8107
Eric Laurente552edb2014-03-10 17:42:56 -07008108}; // namespace android