blob: bd22e427a890680c28ef11fb740ecac23771e9c8 [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 Laurentdf3dc7e2014-07-27 18:39:40 -070046#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070047#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070048#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
52// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070053// Definitions for audio_policy.conf file parsing
54// ----------------------------------------------------------------------------
55
56struct StringToEnum {
57 const char *name;
58 uint32_t value;
59};
60
61#define STRING_TO_ENUM(string) { #string, string }
62#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
63
64const StringToEnum sDeviceNameToEnumTable[] = {
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
Jon Eklund11c9fb12014-06-23 14:47:03 -050067 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER_SAFE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070068 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070079 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070086 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
87 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
90 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070091 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050092 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070093 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700101 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
105 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700106 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700107 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
108 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
110 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700111 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900112 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700113};
114
Eric Laurent5dbe4712014-09-19 19:04:57 -0700115const StringToEnum sOutputFlagNameToEnumTable[] = {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700116 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
Eric Laurent93c3d412014-08-01 14:48:35 -0700122 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700123};
124
Eric Laurent5dbe4712014-09-19 19:04:57 -0700125const StringToEnum sInputFlagNameToEnumTable[] = {
126 STRING_TO_ENUM(AUDIO_INPUT_FLAG_FAST),
127 STRING_TO_ENUM(AUDIO_INPUT_FLAG_HW_HOTWORD),
128};
129
Eric Laurent3a4311c2014-03-17 12:00:47 -0700130const StringToEnum sFormatNameToEnumTable[] = {
131 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
132 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
133 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
134 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
135 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
136 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
137 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
138 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530139 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
143 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
144 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
145 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
146 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
147 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
148 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700149 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700150 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
151 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
152 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
153 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
154 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700155};
156
157const StringToEnum sOutChannelsNameToEnumTable[] = {
158 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
159 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700160 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700161 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
162 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
163};
164
165const StringToEnum sInChannelsNameToEnumTable[] = {
166 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
167 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
168 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
169};
170
Eric Laurent1afeecb2014-05-14 08:52:28 -0700171const StringToEnum sGainModeNameToEnumTable[] = {
172 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
173 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
174 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
175};
176
Eric Laurent3a4311c2014-03-17 12:00:47 -0700177
178uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
179 size_t size,
180 const char *name)
181{
182 for (size_t i = 0; i < size; i++) {
183 if (strcmp(table[i].name, name) == 0) {
184 ALOGV("stringToEnum() found %s", table[i].name);
185 return table[i].value;
186 }
187 }
188 return 0;
189}
190
191const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
192 size_t size,
193 uint32_t value)
194{
195 for (size_t i = 0; i < size; i++) {
196 if (table[i].value == value) {
197 return table[i].name;
198 }
199 }
200 return "";
201}
202
203bool AudioPolicyManager::stringToBool(const char *value)
204{
205 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
206}
207
208
209// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700210// AudioPolicyInterface implementation
211// ----------------------------------------------------------------------------
212
213
Eric Laurente0720872014-03-11 09:30:41 -0700214status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700215 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700216 const char *device_address)
217{
Eric Laurent22226012014-08-01 17:00:54 -0700218 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700219 // handle legacy remote submix case where the address was not always specified
220 if (deviceDistinguishesOnAddress(device) && (address.length() == 0)) {
221 address = String8("0");
222 }
Eric Laurente552edb2014-03-10 17:42:56 -0700223
Eric Laurent22226012014-08-01 17:00:54 -0700224 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
225 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700226
227 // connect/disconnect only 1 device at a time
228 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
229
Eric Laurente552edb2014-03-10 17:42:56 -0700230 // handle output devices
231 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700232 SortedVector <audio_io_handle_t> outputs;
233
Eric Laurent1afeecb2014-05-14 08:52:28 -0700234 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
235 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700236 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
237
Eric Laurente552edb2014-03-10 17:42:56 -0700238 // save a copy of the opened output descriptors before any output is opened or closed
239 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
240 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700241 switch (state)
242 {
243 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700244 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700245 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700246 ALOGW("setDeviceConnectionState() device already connected: %x", device);
247 return INVALID_OPERATION;
248 }
249 ALOGV("setDeviceConnectionState() connecting device %x", device);
250
Eric Laurente552edb2014-03-10 17:42:56 -0700251 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 index = mAvailableOutputDevices.add(devDesc);
253 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700254 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700255 if (module == 0) {
256 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
257 device);
258 mAvailableOutputDevices.remove(devDesc);
259 return INVALID_OPERATION;
260 }
261 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700262 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700263 } else {
264 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700265 }
266
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700267 if (checkOutputsForDevice(devDesc, state, outputs, address) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700268 mAvailableOutputDevices.remove(devDesc);
269 return INVALID_OPERATION;
270 }
271 // outputs should never be empty here
272 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
273 "checkOutputsForDevice() returned no outputs but status OK");
274 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
275 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700276 break;
277 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700278 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700279 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700280 ALOGW("setDeviceConnectionState() device not connected: %x", device);
281 return INVALID_OPERATION;
282 }
283
Paul McLean5c477aa2014-08-20 16:47:57 -0700284 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
285
286 // Set Disconnect to HALs
287 AudioParameter param = AudioParameter(address);
288 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
289 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
290
Eric Laurente552edb2014-03-10 17:42:56 -0700291 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700292 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700293
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700294 checkOutputsForDevice(devDesc, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700295 } break;
296
297 default:
298 ALOGE("setDeviceConnectionState() invalid state: %x", state);
299 return BAD_VALUE;
300 }
301
Eric Laurent3a4311c2014-03-17 12:00:47 -0700302 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
303 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700304 checkA2dpSuspend();
305 checkOutputForAllStrategies();
306 // outputs must be closed after checkOutputForAllStrategies() is executed
307 if (!outputs.isEmpty()) {
308 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700309 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700310 // close unused outputs after device disconnection or direct outputs that have been
311 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700312 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700313 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
314 (desc->mDirectOpenCount == 0))) {
315 closeOutput(outputs[i]);
316 }
317 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700318 // check again after closing A2DP output to reset mA2dpSuspended if needed
319 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700320 }
321
322 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700323 if (mPhoneState == AUDIO_MODE_IN_CALL) {
324 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
325 updateCallRouting(newDevice);
326 }
Eric Laurente552edb2014-03-10 17:42:56 -0700327 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700328 audio_io_handle_t output = mOutputs.keyAt(i);
329 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
330 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
331 true /*fromCache*/);
332 // do not force device change on duplicated output because if device is 0, it will
333 // also force a device 0 for the two outputs it is duplicated to which may override
334 // a valid device selection on those outputs.
335 bool force = !mOutputs.valueAt(i)->isDuplicated()
336 && (!deviceDistinguishesOnAddress(device)
337 // always force when disconnecting (a non-duplicated device)
338 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
339 setOutputDevice(output, newDevice, force, 0);
340 }
Eric Laurente552edb2014-03-10 17:42:56 -0700341 }
342
Eric Laurent72aa32f2014-05-30 18:51:48 -0700343 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700344 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700345 } // end if is output device
346
Eric Laurente552edb2014-03-10 17:42:56 -0700347 // handle input devices
348 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700349 SortedVector <audio_io_handle_t> inputs;
350
Eric Laurent1afeecb2014-05-14 08:52:28 -0700351 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
352 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700353 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700354 switch (state)
355 {
356 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700357 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700358 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700359 ALOGW("setDeviceConnectionState() device already connected: %d", device);
360 return INVALID_OPERATION;
361 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700362 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700363 if (module == NULL) {
364 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
365 device);
366 return INVALID_OPERATION;
367 }
Eric Laurentd4692962014-05-05 18:13:44 -0700368 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
369 return INVALID_OPERATION;
370 }
371
Eric Laurent3a4311c2014-03-17 12:00:47 -0700372 index = mAvailableInputDevices.add(devDesc);
373 if (index >= 0) {
374 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700375 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700376 } else {
377 return NO_MEMORY;
378 }
Eric Laurentd4692962014-05-05 18:13:44 -0700379 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700380
381 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700382 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700383 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700384 ALOGW("setDeviceConnectionState() device not connected: %d", device);
385 return INVALID_OPERATION;
386 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700387
388 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
389
390 // Set Disconnect to HALs
391 AudioParameter param = AudioParameter(address);
392 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
393 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
394
Eric Laurentd4692962014-05-05 18:13:44 -0700395 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700396 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700397
Eric Laurentd4692962014-05-05 18:13:44 -0700398 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700399
400 default:
401 ALOGE("setDeviceConnectionState() invalid state: %x", state);
402 return BAD_VALUE;
403 }
404
Eric Laurentd4692962014-05-05 18:13:44 -0700405 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700406
Eric Laurentc2730ba2014-07-20 15:47:07 -0700407 if (mPhoneState == AUDIO_MODE_IN_CALL) {
408 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
409 updateCallRouting(newDevice);
410 }
411
Eric Laurentb52c1522014-05-20 11:27:36 -0700412 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700413 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700414 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700415
416 ALOGW("setDeviceConnectionState() invalid device: %x", device);
417 return BAD_VALUE;
418}
419
Eric Laurente0720872014-03-11 09:30:41 -0700420audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700421 const char *device_address)
422{
Eric Laurent3b73df72014-03-11 09:06:29 -0700423 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700424 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700425 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700426 // handle legacy remote submix case where the address was not always specified
427 if (deviceDistinguishesOnAddress(device) && (devDesc->mAddress.length() == 0)) {
428 devDesc->mAddress = String8("0");
429 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700430 ssize_t index;
431 DeviceVector *deviceVector;
432
Eric Laurente552edb2014-03-10 17:42:56 -0700433 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700434 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700435 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700436 deviceVector = &mAvailableInputDevices;
437 } else {
438 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
439 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700440 }
441
Eric Laurent3a4311c2014-03-17 12:00:47 -0700442 index = deviceVector->indexOf(devDesc);
443 if (index >= 0) {
444 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
445 } else {
446 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
447 }
Eric Laurente552edb2014-03-10 17:42:56 -0700448}
449
Eric Laurentc2730ba2014-07-20 15:47:07 -0700450void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
451{
452 bool createTxPatch = false;
453 struct audio_patch patch;
454 patch.num_sources = 1;
455 patch.num_sinks = 1;
456 status_t status;
457 audio_patch_handle_t afPatchHandle;
458 DeviceVector deviceList;
459
460 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
461 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
462
463 // release existing RX patch if any
464 if (mCallRxPatch != 0) {
465 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
466 mCallRxPatch.clear();
467 }
468 // release TX patch if any
469 if (mCallTxPatch != 0) {
470 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
471 mCallTxPatch.clear();
472 }
473
474 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
475 // via setOutputDevice() on primary output.
476 // Otherwise, create two audio patches for TX and RX path.
477 if (availablePrimaryOutputDevices() & rxDevice) {
478 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
479 // If the TX device is also on the primary HW module, setOutputDevice() will take care
480 // of it due to legacy implementation. If not, create a patch.
481 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
482 == AUDIO_DEVICE_NONE) {
483 createTxPatch = true;
484 }
485 } else {
486 // create RX path audio patch
487 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
488 ALOG_ASSERT(!deviceList.isEmpty(),
489 "updateCallRouting() selected device not in output device list");
490 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
491 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
492 ALOG_ASSERT(!deviceList.isEmpty(),
493 "updateCallRouting() no telephony RX device");
494 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
495
496 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
497 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
498
499 // request to reuse existing output stream if one is already opened to reach the RX device
500 SortedVector<audio_io_handle_t> outputs =
501 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700502 audio_io_handle_t output = selectOutput(outputs,
503 AUDIO_OUTPUT_FLAG_NONE,
504 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700505 if (output != AUDIO_IO_HANDLE_NONE) {
506 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
507 ALOG_ASSERT(!outputDesc->isDuplicated(),
508 "updateCallRouting() RX device output is duplicated");
509 outputDesc->toAudioPortConfig(&patch.sources[1]);
510 patch.num_sources = 2;
511 }
512
513 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
514 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
515 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
516 status);
517 if (status == NO_ERROR) {
518 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
519 &patch, mUidCached);
520 mCallRxPatch->mAfPatchHandle = afPatchHandle;
521 mCallRxPatch->mUid = mUidCached;
522 }
523 createTxPatch = true;
524 }
525 if (createTxPatch) {
526
527 struct audio_patch patch;
528 patch.num_sources = 1;
529 patch.num_sinks = 1;
530 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
531 ALOG_ASSERT(!deviceList.isEmpty(),
532 "updateCallRouting() selected device not in input device list");
533 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
534 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
535 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
536 ALOG_ASSERT(!deviceList.isEmpty(),
537 "updateCallRouting() no telephony TX device");
538 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
539 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
540
541 SortedVector<audio_io_handle_t> outputs =
542 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700543 audio_io_handle_t output = selectOutput(outputs,
544 AUDIO_OUTPUT_FLAG_NONE,
545 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700546 // request to reuse existing output stream if one is already opened to reach the TX
547 // path output device
548 if (output != AUDIO_IO_HANDLE_NONE) {
549 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
550 ALOG_ASSERT(!outputDesc->isDuplicated(),
551 "updateCallRouting() RX device output is duplicated");
552 outputDesc->toAudioPortConfig(&patch.sources[1]);
553 patch.num_sources = 2;
554 }
555
556 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
557 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
558 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
559 status);
560 if (status == NO_ERROR) {
561 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
562 &patch, mUidCached);
563 mCallTxPatch->mAfPatchHandle = afPatchHandle;
564 mCallTxPatch->mUid = mUidCached;
565 }
566 }
567}
568
Eric Laurente0720872014-03-11 09:30:41 -0700569void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700570{
571 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700572 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700573 ALOGW("setPhoneState() invalid state %d", state);
574 return;
575 }
576
577 if (state == mPhoneState ) {
578 ALOGW("setPhoneState() setting same state %d", state);
579 return;
580 }
581
582 // if leaving call state, handle special case of active streams
583 // pertaining to sonification strategy see handleIncallSonification()
584 if (isInCall()) {
585 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700586 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
587 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700588 }
589 }
590
591 // store previous phone state for management of sonification strategy below
592 int oldState = mPhoneState;
593 mPhoneState = state;
594 bool force = false;
595
596 // are we entering or starting a call
597 if (!isStateInCall(oldState) && isStateInCall(state)) {
598 ALOGV(" Entering call in setPhoneState()");
599 // force routing command to audio hardware when starting a call
600 // even if no device change is needed
601 force = true;
602 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
603 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
604 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
605 }
606 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
607 ALOGV(" Exiting call in setPhoneState()");
608 // force routing command to audio hardware when exiting a call
609 // even if no device change is needed
610 force = true;
611 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
612 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
613 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
614 }
615 } else if (isStateInCall(state) && (state != oldState)) {
616 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
617 // force routing command to audio hardware when switching between telephony and VoIP
618 // even if no device change is needed
619 force = true;
620 }
621
622 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700623 checkA2dpSuspend();
624 checkOutputForAllStrategies();
625 updateDevicesAndOutputs();
626
Eric Laurent1f2f2232014-06-02 12:01:23 -0700627 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700628
Eric Laurente552edb2014-03-10 17:42:56 -0700629 int delayMs = 0;
630 if (isStateInCall(state)) {
631 nsecs_t sysTime = systemTime();
632 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700633 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700634 // mute media and sonification strategies and delay device switch by the largest
635 // latency of any output where either strategy is active.
636 // This avoid sending the ring tone or music tail into the earpiece or headset.
637 if ((desc->isStrategyActive(STRATEGY_MEDIA,
638 SONIFICATION_HEADSET_MUSIC_DELAY,
639 sysTime) ||
640 desc->isStrategyActive(STRATEGY_SONIFICATION,
641 SONIFICATION_HEADSET_MUSIC_DELAY,
642 sysTime)) &&
643 (delayMs < (int)desc->mLatency*2)) {
644 delayMs = desc->mLatency*2;
645 }
646 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
647 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
648 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
649 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
650 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
651 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
652 }
653 }
654
Eric Laurentc2730ba2014-07-20 15:47:07 -0700655 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
656 // the device returned is not necessarily reachable via this output
657 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
658 // force routing command to audio hardware when ending call
659 // even if no device change is needed
660 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
661 rxDevice = hwOutputDesc->device();
662 }
Eric Laurente552edb2014-03-10 17:42:56 -0700663
Eric Laurentc2730ba2014-07-20 15:47:07 -0700664 if (state == AUDIO_MODE_IN_CALL) {
665 updateCallRouting(rxDevice, delayMs);
666 } else if (oldState == AUDIO_MODE_IN_CALL) {
667 if (mCallRxPatch != 0) {
668 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
669 mCallRxPatch.clear();
670 }
671 if (mCallTxPatch != 0) {
672 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
673 mCallTxPatch.clear();
674 }
675 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
676 } else {
677 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
678 }
Eric Laurente552edb2014-03-10 17:42:56 -0700679 // if entering in call state, handle special case of active streams
680 // pertaining to sonification strategy see handleIncallSonification()
681 if (isStateInCall(state)) {
682 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700683 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
684 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700685 }
686 }
687
688 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700689 if (state == AUDIO_MODE_RINGTONE &&
690 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700691 mLimitRingtoneVolume = true;
692 } else {
693 mLimitRingtoneVolume = false;
694 }
695}
696
Eric Laurente0720872014-03-11 09:30:41 -0700697void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700698 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700699{
700 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
701
702 bool forceVolumeReeval = false;
703 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700704 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
705 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
706 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700707 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
708 return;
709 }
710 forceVolumeReeval = true;
711 mForceUse[usage] = config;
712 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700713 case AUDIO_POLICY_FORCE_FOR_MEDIA:
714 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
715 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
716 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
717 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Hochi Huang327cb702014-09-21 09:47:31 +0800718 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
Eric Laurente552edb2014-03-10 17:42:56 -0700719 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
720 return;
721 }
722 mForceUse[usage] = config;
723 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700724 case AUDIO_POLICY_FORCE_FOR_RECORD:
725 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
726 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700727 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
728 return;
729 }
730 mForceUse[usage] = config;
731 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700732 case AUDIO_POLICY_FORCE_FOR_DOCK:
733 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
734 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
735 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
736 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
737 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700738 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
739 }
740 forceVolumeReeval = true;
741 mForceUse[usage] = config;
742 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700743 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
744 if (config != AUDIO_POLICY_FORCE_NONE &&
745 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700746 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
747 }
748 forceVolumeReeval = true;
749 mForceUse[usage] = config;
750 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900751 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
752 if (config != AUDIO_POLICY_FORCE_NONE &&
753 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
754 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
755 }
756 mForceUse[usage] = config;
757 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700758 default:
759 ALOGW("setForceUse() invalid usage %d", usage);
760 break;
761 }
762
763 // check for device and output changes triggered by new force usage
764 checkA2dpSuspend();
765 checkOutputForAllStrategies();
766 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700767 if (mPhoneState == AUDIO_MODE_IN_CALL) {
768 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
769 updateCallRouting(newDevice);
770 }
Eric Laurente552edb2014-03-10 17:42:56 -0700771 for (size_t i = 0; i < mOutputs.size(); i++) {
772 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700773 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700774 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
775 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
776 }
Eric Laurente552edb2014-03-10 17:42:56 -0700777 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
778 applyStreamVolumes(output, newDevice, 0, true);
779 }
780 }
781
782 audio_io_handle_t activeInput = getActiveInput();
783 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700784 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700785 }
786
787}
788
Eric Laurente0720872014-03-11 09:30:41 -0700789audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700790{
791 return mForceUse[usage];
792}
793
Eric Laurente0720872014-03-11 09:30:41 -0700794void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700795{
796 ALOGV("setSystemProperty() property %s, value %s", property, value);
797}
798
799// Find a direct output profile compatible with the parameters passed, even if the input flags do
800// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700801sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700802 audio_devices_t device,
803 uint32_t samplingRate,
804 audio_format_t format,
805 audio_channel_mask_t channelMask,
806 audio_output_flags_t flags)
807{
808 for (size_t i = 0; i < mHwModules.size(); i++) {
809 if (mHwModules[i]->mHandle == 0) {
810 continue;
811 }
812 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700813 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700814 bool found = profile->isCompatibleProfile(device, samplingRate,
815 NULL /*updatedSamplingRate*/, format, channelMask,
816 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
817 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700818 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
819 return profile;
820 }
Eric Laurente552edb2014-03-10 17:42:56 -0700821 }
822 }
823 return 0;
824}
825
Eric Laurente0720872014-03-11 09:30:41 -0700826audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700827 uint32_t samplingRate,
828 audio_format_t format,
829 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700830 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700831 const audio_offload_info_t *offloadInfo)
832{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700833
Eric Laurent3b73df72014-03-11 09:06:29 -0700834 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700835 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
836 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
837 device, stream, samplingRate, format, channelMask, flags);
838
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700839 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
840 offloadInfo);
841}
842
843audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
844 uint32_t samplingRate,
845 audio_format_t format,
846 audio_channel_mask_t channelMask,
847 audio_output_flags_t flags,
848 const audio_offload_info_t *offloadInfo)
849{
850 if (attr == NULL) {
851 ALOGE("getOutputForAttr() called with NULL audio attributes");
852 return 0;
853 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700854 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
855 attr->usage, attr->content_type, attr->tags, attr->flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700856
857 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
858 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
859 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700860
861 if ((attr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
862 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
863 }
864
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700865 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700866 device, samplingRate, format, channelMask, flags);
867
868 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
869 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
870 offloadInfo);
871}
872
873audio_io_handle_t AudioPolicyManager::getOutputForDevice(
874 audio_devices_t device,
875 audio_stream_type_t stream,
876 uint32_t samplingRate,
877 audio_format_t format,
878 audio_channel_mask_t channelMask,
879 audio_output_flags_t flags,
880 const audio_offload_info_t *offloadInfo)
881{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700882 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700883 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700884 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700885
Eric Laurente552edb2014-03-10 17:42:56 -0700886#ifdef AUDIO_POLICY_TEST
887 if (mCurOutput != 0) {
888 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
889 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
890
891 if (mTestOutputs[mCurOutput] == 0) {
892 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700893 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700894 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700895 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700896 outputDesc->mFlags =
897 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700898 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700899 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
900 config.sample_rate = mTestSamplingRate;
901 config.channel_mask = mTestChannels;
902 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700903 if (offloadInfo != NULL) {
904 config.offload_info = *offloadInfo;
905 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700906 status = mpClientInterface->openOutput(0,
907 &mTestOutputs[mCurOutput],
908 &config,
909 &outputDesc->mDevice,
910 String8(""),
911 &outputDesc->mLatency,
912 outputDesc->mFlags);
913 if (status == NO_ERROR) {
914 outputDesc->mSamplingRate = config.sample_rate;
915 outputDesc->mFormat = config.format;
916 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700917 AudioParameter outputCmd = AudioParameter();
918 outputCmd.addInt(String8("set_id"),mCurOutput);
919 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
920 addOutput(mTestOutputs[mCurOutput], outputDesc);
921 }
922 }
923 return mTestOutputs[mCurOutput];
924 }
925#endif //AUDIO_POLICY_TEST
926
927 // open a direct output if required by specified parameters
928 //force direct flag if offload flag is set: offloading implies a direct output stream
929 // and all common behaviors are driven by checking only the direct flag
930 // this should normally be set appropriately in the policy configuration file
931 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700932 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700933 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700934 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
935 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
936 }
Eric Laurente552edb2014-03-10 17:42:56 -0700937
Eric Laurentb732cf52014-09-24 19:08:21 -0700938 sp<IOProfile> profile;
939
940 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700941 // and not explicitly requested
942 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
943 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700944 audio_channel_count_from_out_mask(channelMask) <= 2) {
945 goto non_direct_output;
946 }
947
Eric Laurente552edb2014-03-10 17:42:56 -0700948 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
949 // creating an offloaded track and tearing it down immediately after start when audioflinger
950 // detects there is an active non offloadable effect.
951 // FIXME: We should check the audio session here but we do not have it in this context.
952 // This may prevent offloading in rare situations where effects are left active by apps
953 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700954
Eric Laurente552edb2014-03-10 17:42:56 -0700955 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
956 !isNonOffloadableEffectEnabled()) {
957 profile = getProfileForDirectOutput(device,
958 samplingRate,
959 format,
960 channelMask,
961 (audio_output_flags_t)flags);
962 }
963
Eric Laurent1c333e22014-05-20 10:48:17 -0700964 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700965 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700966
967 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700968 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700969 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
970 outputDesc = desc;
971 // reuse direct output if currently open and configured with same parameters
972 if ((samplingRate == outputDesc->mSamplingRate) &&
973 (format == outputDesc->mFormat) &&
974 (channelMask == outputDesc->mChannelMask)) {
975 outputDesc->mDirectOpenCount++;
976 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
977 return mOutputs.keyAt(i);
978 }
979 }
980 }
981 // close direct output if currently open and configured with different parameters
982 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700983 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700984 }
985 outputDesc = new AudioOutputDescriptor(profile);
986 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700987 outputDesc->mLatency = 0;
988 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700989 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
990 config.sample_rate = samplingRate;
991 config.channel_mask = channelMask;
992 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700993 if (offloadInfo != NULL) {
994 config.offload_info = *offloadInfo;
995 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700996 status = mpClientInterface->openOutput(profile->mModule->mHandle,
997 &output,
998 &config,
999 &outputDesc->mDevice,
1000 String8(""),
1001 &outputDesc->mLatency,
1002 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001003
1004 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001005 if (status != NO_ERROR ||
1006 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1007 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1008 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001009 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1010 "format %d %d, channelMask %04x %04x", output, samplingRate,
1011 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1012 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001013 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001014 mpClientInterface->closeOutput(output);
1015 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001016 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001017 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001018 outputDesc->mSamplingRate = config.sample_rate;
1019 outputDesc->mChannelMask = config.channel_mask;
1020 outputDesc->mFormat = config.format;
1021 outputDesc->mRefCount[stream] = 0;
1022 outputDesc->mStopTime[stream] = 0;
1023 outputDesc->mDirectOpenCount = 1;
1024
Eric Laurente552edb2014-03-10 17:42:56 -07001025 audio_io_handle_t srcOutput = getOutputForEffect();
1026 addOutput(output, outputDesc);
1027 audio_io_handle_t dstOutput = getOutputForEffect();
1028 if (dstOutput == output) {
1029 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1030 }
1031 mPreviousOutputs = mOutputs;
1032 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001033 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001034 return output;
1035 }
1036
Eric Laurentb732cf52014-09-24 19:08:21 -07001037non_direct_output:
1038
Eric Laurente552edb2014-03-10 17:42:56 -07001039 // ignoring channel mask due to downmix capability in mixer
1040
1041 // open a non direct output
1042
1043 // for non direct outputs, only PCM is supported
1044 if (audio_is_linear_pcm(format)) {
1045 // get which output is suitable for the specified stream. The actual
1046 // routing change will happen when startOutput() will be called
1047 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1048
Eric Laurent8838a382014-09-08 16:44:28 -07001049 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1050 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1051 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001052 }
1053 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1054 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1055
1056 ALOGV("getOutput() returns output %d", output);
1057
1058 return output;
1059}
1060
Eric Laurente0720872014-03-11 09:30:41 -07001061audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001062 audio_output_flags_t flags,
1063 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001064{
1065 // select one output among several that provide a path to a particular device or set of
1066 // devices (the list was previously build by getOutputsForDevice()).
1067 // The priority is as follows:
1068 // 1: the output with the highest number of requested policy flags
1069 // 2: the primary output
1070 // 3: the first output in the list
1071
1072 if (outputs.size() == 0) {
1073 return 0;
1074 }
1075 if (outputs.size() == 1) {
1076 return outputs[0];
1077 }
1078
1079 int maxCommonFlags = 0;
1080 audio_io_handle_t outputFlags = 0;
1081 audio_io_handle_t outputPrimary = 0;
1082
1083 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001084 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001085 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001086 // if a valid format is specified, skip output if not compatible
1087 if (format != AUDIO_FORMAT_INVALID) {
1088 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1089 if (format != outputDesc->mFormat) {
1090 continue;
1091 }
1092 } else if (!audio_is_linear_pcm(format)) {
1093 continue;
1094 }
1095 }
1096
Eric Laurent3b73df72014-03-11 09:06:29 -07001097 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001098 if (commonFlags > maxCommonFlags) {
1099 outputFlags = outputs[i];
1100 maxCommonFlags = commonFlags;
1101 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1102 }
1103 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1104 outputPrimary = outputs[i];
1105 }
1106 }
1107 }
1108
1109 if (outputFlags != 0) {
1110 return outputFlags;
1111 }
1112 if (outputPrimary != 0) {
1113 return outputPrimary;
1114 }
1115
1116 return outputs[0];
1117}
1118
Eric Laurente0720872014-03-11 09:30:41 -07001119status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001120 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001121 int session)
1122{
1123 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1124 ssize_t index = mOutputs.indexOfKey(output);
1125 if (index < 0) {
1126 ALOGW("startOutput() unknown output %d", output);
1127 return BAD_VALUE;
1128 }
1129
Eric Laurent1f2f2232014-06-02 12:01:23 -07001130 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001131
1132 // increment usage count for this stream on the requested output:
1133 // NOTE that the usage count is the same for duplicated output and hardware output which is
1134 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1135 outputDesc->changeRefCount(stream, 1);
1136
1137 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001138 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001139 routing_strategy strategy = getStrategy(stream);
1140 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1141 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
1142 uint32_t waitMs = 0;
1143 bool force = false;
1144 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001145 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001146 if (desc != outputDesc) {
1147 // force a device change if any other output is managed by the same hw
1148 // module and has a current device selection that differs from selected device.
1149 // In this case, the audio HAL must receive the new device selection so that it can
1150 // change the device currently selected by the other active output.
1151 if (outputDesc->sharesHwModuleWith(desc) &&
1152 desc->device() != newDevice) {
1153 force = true;
1154 }
1155 // wait for audio on other active outputs to be presented when starting
1156 // a notification so that audio focus effect can propagate.
1157 uint32_t latency = desc->latency();
1158 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1159 waitMs = latency;
1160 }
1161 }
1162 }
1163 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1164
1165 // handle special case for sonification while in call
1166 if (isInCall()) {
1167 handleIncallSonification(stream, true, false);
1168 }
1169
1170 // apply volume rules for current stream and device if necessary
1171 checkAndSetVolume(stream,
1172 mStreams[stream].getVolumeIndex(newDevice),
1173 output,
1174 newDevice);
1175
1176 // update the outputs if starting an output with a stream that can affect notification
1177 // routing
1178 handleNotificationRoutingForStream(stream);
1179 if (waitMs > muteWaitMs) {
1180 usleep((waitMs - muteWaitMs) * 2 * 1000);
1181 }
1182 }
1183 return NO_ERROR;
1184}
1185
1186
Eric Laurente0720872014-03-11 09:30:41 -07001187status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001188 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001189 int session)
1190{
1191 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1192 ssize_t index = mOutputs.indexOfKey(output);
1193 if (index < 0) {
1194 ALOGW("stopOutput() unknown output %d", output);
1195 return BAD_VALUE;
1196 }
1197
Eric Laurent1f2f2232014-06-02 12:01:23 -07001198 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001199
1200 // handle special case for sonification while in call
1201 if (isInCall()) {
1202 handleIncallSonification(stream, false, false);
1203 }
1204
1205 if (outputDesc->mRefCount[stream] > 0) {
1206 // decrement usage count of this stream on the output
1207 outputDesc->changeRefCount(stream, -1);
1208 // store time at which the stream was stopped - see isStreamActive()
1209 if (outputDesc->mRefCount[stream] == 0) {
1210 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001211 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001212 // delay the device switch by twice the latency because stopOutput() is executed when
1213 // the track stop() command is received and at that time the audio track buffer can
1214 // still contain data that needs to be drained. The latency only covers the audio HAL
1215 // and kernel buffers. Also the latency does not always include additional delay in the
1216 // audio path (audio DSP, CODEC ...)
1217 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1218
1219 // force restoring the device selection on other active outputs if it differs from the
1220 // one being selected for this output
1221 for (size_t i = 0; i < mOutputs.size(); i++) {
1222 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001223 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001224 if (curOutput != output &&
1225 desc->isActive() &&
1226 outputDesc->sharesHwModuleWith(desc) &&
1227 (newDevice != desc->device())) {
1228 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001229 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001230 true,
1231 outputDesc->mLatency*2);
1232 }
1233 }
1234 // update the outputs if stopping one with a stream that can affect notification routing
1235 handleNotificationRoutingForStream(stream);
1236 }
1237 return NO_ERROR;
1238 } else {
1239 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1240 return INVALID_OPERATION;
1241 }
1242}
1243
Eric Laurente0720872014-03-11 09:30:41 -07001244void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001245{
1246 ALOGV("releaseOutput() %d", output);
1247 ssize_t index = mOutputs.indexOfKey(output);
1248 if (index < 0) {
1249 ALOGW("releaseOutput() releasing unknown output %d", output);
1250 return;
1251 }
1252
1253#ifdef AUDIO_POLICY_TEST
1254 int testIndex = testOutputIndex(output);
1255 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001256 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001257 if (outputDesc->isActive()) {
1258 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001259 mOutputs.removeItem(output);
1260 mTestOutputs[testIndex] = 0;
1261 }
1262 return;
1263 }
1264#endif //AUDIO_POLICY_TEST
1265
Eric Laurent1f2f2232014-06-02 12:01:23 -07001266 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001267 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001268 if (desc->mDirectOpenCount <= 0) {
1269 ALOGW("releaseOutput() invalid open count %d for output %d",
1270 desc->mDirectOpenCount, output);
1271 return;
1272 }
1273 if (--desc->mDirectOpenCount == 0) {
1274 closeOutput(output);
1275 // If effects where present on the output, audioflinger moved them to the primary
1276 // output by default: move them back to the appropriate output.
1277 audio_io_handle_t dstOutput = getOutputForEffect();
1278 if (dstOutput != mPrimaryOutput) {
1279 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1280 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001281 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001282 }
1283 }
1284}
1285
1286
Eric Laurente0720872014-03-11 09:30:41 -07001287audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001288 uint32_t samplingRate,
1289 audio_format_t format,
1290 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001291 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001292 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001293{
Eric Laurent4dc68062014-07-28 17:26:49 -07001294 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001295 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001296 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001297
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001298 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001299
1300 if (device == AUDIO_DEVICE_NONE) {
1301 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001302 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001303 }
1304
1305 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001306 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001307 case AUDIO_SOURCE_VOICE_UPLINK:
1308 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1309 break;
1310 case AUDIO_SOURCE_VOICE_DOWNLINK:
1311 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1312 break;
1313 case AUDIO_SOURCE_VOICE_CALL:
1314 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1315 break;
1316 default:
1317 break;
1318 }
1319
Eric Laurent5dbe4712014-09-19 19:04:57 -07001320 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1321 bool isSoundTrigger = false;
1322 audio_source_t halInputSource = inputSource;
1323 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1324 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1325 if (index >= 0) {
1326 input = mSoundTriggerSessions.valueFor(session);
1327 isSoundTrigger = true;
1328 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1329 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1330 } else {
1331 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1332 }
1333 }
1334
Eric Laurent1c333e22014-05-20 10:48:17 -07001335 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001336 samplingRate,
1337 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001338 channelMask,
1339 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001340 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001341 //retry without flags
1342 audio_input_flags_t log_flags = flags;
1343 flags = AUDIO_INPUT_FLAG_NONE;
1344 profile = getInputProfile(device,
1345 samplingRate,
1346 format,
1347 channelMask,
1348 flags);
1349 if (profile == 0) {
1350 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1351 "channelMask 0x%X, flags %#x",
1352 device, samplingRate, format, channelMask, log_flags);
1353 return AUDIO_IO_HANDLE_NONE;
1354 }
Eric Laurente552edb2014-03-10 17:42:56 -07001355 }
1356
1357 if (profile->mModule->mHandle == 0) {
1358 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001359 return AUDIO_IO_HANDLE_NONE;
1360 }
1361
1362 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1363 config.sample_rate = samplingRate;
1364 config.channel_mask = channelMask;
1365 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001366
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001367 // handle legacy remote submix case where the address was not always specified
1368 String8 address = deviceDistinguishesOnAddress(device) ? String8("0") : String8("");
1369
Eric Laurentcf2c0212014-07-25 16:20:43 -07001370 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1371 &input,
1372 &config,
1373 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001374 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001375 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001376 flags);
1377
1378 // only accept input with the exact requested set of parameters
1379 if (status != NO_ERROR ||
1380 (samplingRate != config.sample_rate) ||
1381 (format != config.format) ||
1382 (channelMask != config.channel_mask)) {
1383 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1384 samplingRate, format, channelMask);
1385 if (input != AUDIO_IO_HANDLE_NONE) {
1386 mpClientInterface->closeInput(input);
1387 }
1388 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001389 }
1390
Eric Laurent1f2f2232014-06-02 12:01:23 -07001391 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001392 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001393 inputDesc->mRefCount = 0;
1394 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001395 inputDesc->mSamplingRate = samplingRate;
1396 inputDesc->mFormat = format;
1397 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001398 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001399 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001400 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001401
Eric Laurentd4692962014-05-05 18:13:44 -07001402 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001403 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001404 return input;
1405}
1406
Eric Laurent4dc68062014-07-28 17:26:49 -07001407status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1408 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001409{
1410 ALOGV("startInput() input %d", input);
1411 ssize_t index = mInputs.indexOfKey(input);
1412 if (index < 0) {
1413 ALOGW("startInput() unknown input %d", input);
1414 return BAD_VALUE;
1415 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001416 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001417
Eric Laurent4dc68062014-07-28 17:26:49 -07001418 index = inputDesc->mSessions.indexOf(session);
1419 if (index < 0) {
1420 ALOGW("startInput() unknown session %d on input %d", session, input);
1421 return BAD_VALUE;
1422 }
1423
Glenn Kasten74a8e252014-07-24 14:09:55 -07001424 // virtual input devices are compatible with other input devices
1425 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1426
1427 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001428 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001429 if (activeInput != 0 && activeInput != input) {
1430
1431 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1432 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001433 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001434 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001435 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001436 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1437 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001438 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001439 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001440 return INVALID_OPERATION;
1441 }
1442 }
1443 }
1444
Glenn Kasten74a8e252014-07-24 14:09:55 -07001445 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001446 if (activeInputsCount() == 0) {
1447 SoundTrigger::setCaptureState(true);
1448 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001449 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001450
Glenn Kasten74a8e252014-07-24 14:09:55 -07001451 // Automatically enable the remote submix output when input is started.
1452 // For remote submix (a virtual device), we open only one input per capture request.
1453 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1454 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1455 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1456 }
Eric Laurente552edb2014-03-10 17:42:56 -07001457 }
1458
Eric Laurente552edb2014-03-10 17:42:56 -07001459 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1460
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001461 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001462 return NO_ERROR;
1463}
1464
Eric Laurent4dc68062014-07-28 17:26:49 -07001465status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1466 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001467{
1468 ALOGV("stopInput() input %d", input);
1469 ssize_t index = mInputs.indexOfKey(input);
1470 if (index < 0) {
1471 ALOGW("stopInput() unknown input %d", input);
1472 return BAD_VALUE;
1473 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001474 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001475
Eric Laurent4dc68062014-07-28 17:26:49 -07001476 index = inputDesc->mSessions.indexOf(session);
1477 if (index < 0) {
1478 ALOGW("stopInput() unknown session %d on input %d", session, input);
1479 return BAD_VALUE;
1480 }
1481
Eric Laurente552edb2014-03-10 17:42:56 -07001482 if (inputDesc->mRefCount == 0) {
1483 ALOGW("stopInput() input %d already stopped", input);
1484 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001485 }
1486
1487 inputDesc->mRefCount--;
1488 if (inputDesc->mRefCount == 0) {
1489
Eric Laurente552edb2014-03-10 17:42:56 -07001490 // automatically disable the remote submix output when input is stopped
1491 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1492 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001493 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001494 }
1495
Eric Laurent1c333e22014-05-20 10:48:17 -07001496 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001497
1498 if (activeInputsCount() == 0) {
1499 SoundTrigger::setCaptureState(false);
1500 }
Eric Laurente552edb2014-03-10 17:42:56 -07001501 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001502 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001503}
1504
Eric Laurent4dc68062014-07-28 17:26:49 -07001505void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1506 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001507{
1508 ALOGV("releaseInput() %d", input);
1509 ssize_t index = mInputs.indexOfKey(input);
1510 if (index < 0) {
1511 ALOGW("releaseInput() releasing unknown input %d", input);
1512 return;
1513 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001514 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1515 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001516
1517 index = inputDesc->mSessions.indexOf(session);
1518 if (index < 0) {
1519 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1520 return;
1521 }
1522 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001523 if (inputDesc->mOpenRefCount == 0) {
1524 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1525 return;
1526 }
1527 inputDesc->mOpenRefCount--;
1528 if (inputDesc->mOpenRefCount > 0) {
1529 ALOGV("releaseInput() exit > 0");
1530 return;
1531 }
1532
Eric Laurent05b90f82014-08-27 15:32:29 -07001533 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001534 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001535 ALOGV("releaseInput() exit");
1536}
1537
Eric Laurentd4692962014-05-05 18:13:44 -07001538void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001539 bool patchRemoved = false;
1540
Eric Laurentd4692962014-05-05 18:13:44 -07001541 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001542 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1543 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1544 if (patch_index >= 0) {
1545 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1546 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1547 mAudioPatches.removeItemsAt(patch_index);
1548 patchRemoved = true;
1549 }
Eric Laurentd4692962014-05-05 18:13:44 -07001550 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1551 }
1552 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001553 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001554
1555 if (patchRemoved) {
1556 mpClientInterface->onAudioPatchListUpdate();
1557 }
Eric Laurentd4692962014-05-05 18:13:44 -07001558}
1559
Eric Laurente0720872014-03-11 09:30:41 -07001560void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001561 int indexMin,
1562 int indexMax)
1563{
1564 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1565 if (indexMin < 0 || indexMin >= indexMax) {
1566 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1567 return;
1568 }
1569 mStreams[stream].mIndexMin = indexMin;
1570 mStreams[stream].mIndexMax = indexMax;
1571}
1572
Eric Laurente0720872014-03-11 09:30:41 -07001573status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001574 int index,
1575 audio_devices_t device)
1576{
1577
1578 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1579 return BAD_VALUE;
1580 }
1581 if (!audio_is_output_device(device)) {
1582 return BAD_VALUE;
1583 }
1584
1585 // Force max volume if stream cannot be muted
1586 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1587
1588 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1589 stream, device, index);
1590
1591 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1592 // clear all device specific values
1593 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1594 mStreams[stream].mIndexCur.clear();
1595 }
1596 mStreams[stream].mIndexCur.add(device, index);
1597
Eric Laurent31551f82014-10-10 18:21:56 -07001598 // update volume on all outputs whose current device is also selected by the same
1599 // strategy as the device specified by the caller
1600 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1601 if ((device != AUDIO_DEVICE_OUT_DEFAULT) && (device & strategyDevice) == 0) {
1602 return NO_ERROR;
1603 }
Eric Laurente552edb2014-03-10 17:42:56 -07001604 status_t status = NO_ERROR;
1605 for (size_t i = 0; i < mOutputs.size(); i++) {
1606 audio_devices_t curDevice =
1607 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001608 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001609 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1610 if (volStatus != NO_ERROR) {
1611 status = volStatus;
1612 }
1613 }
1614 }
1615 return status;
1616}
1617
Eric Laurente0720872014-03-11 09:30:41 -07001618status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001619 int *index,
1620 audio_devices_t device)
1621{
1622 if (index == NULL) {
1623 return BAD_VALUE;
1624 }
1625 if (!audio_is_output_device(device)) {
1626 return BAD_VALUE;
1627 }
1628 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1629 // the strategy the stream belongs to.
1630 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1631 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1632 }
1633 device = getDeviceForVolume(device);
1634
1635 *index = mStreams[stream].getVolumeIndex(device);
1636 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1637 return NO_ERROR;
1638}
1639
Eric Laurente0720872014-03-11 09:30:41 -07001640audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001641 const SortedVector<audio_io_handle_t>& outputs)
1642{
1643 // select one output among several suitable for global effects.
1644 // The priority is as follows:
1645 // 1: An offloaded output. If the effect ends up not being offloadable,
1646 // AudioFlinger will invalidate the track and the offloaded output
1647 // will be closed causing the effect to be moved to a PCM output.
1648 // 2: A deep buffer output
1649 // 3: the first output in the list
1650
1651 if (outputs.size() == 0) {
1652 return 0;
1653 }
1654
1655 audio_io_handle_t outputOffloaded = 0;
1656 audio_io_handle_t outputDeepBuffer = 0;
1657
1658 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001659 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001660 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001661 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1662 outputOffloaded = outputs[i];
1663 }
1664 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1665 outputDeepBuffer = outputs[i];
1666 }
1667 }
1668
1669 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1670 outputOffloaded, outputDeepBuffer);
1671 if (outputOffloaded != 0) {
1672 return outputOffloaded;
1673 }
1674 if (outputDeepBuffer != 0) {
1675 return outputDeepBuffer;
1676 }
1677
1678 return outputs[0];
1679}
1680
Eric Laurente0720872014-03-11 09:30:41 -07001681audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001682{
1683 // apply simple rule where global effects are attached to the same output as MUSIC streams
1684
Eric Laurent3b73df72014-03-11 09:06:29 -07001685 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001686 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1687 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1688
1689 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1690 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1691 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1692
1693 return output;
1694}
1695
Eric Laurente0720872014-03-11 09:30:41 -07001696status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001697 audio_io_handle_t io,
1698 uint32_t strategy,
1699 int session,
1700 int id)
1701{
1702 ssize_t index = mOutputs.indexOfKey(io);
1703 if (index < 0) {
1704 index = mInputs.indexOfKey(io);
1705 if (index < 0) {
1706 ALOGW("registerEffect() unknown io %d", io);
1707 return INVALID_OPERATION;
1708 }
1709 }
1710
1711 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1712 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1713 desc->name, desc->memoryUsage);
1714 return INVALID_OPERATION;
1715 }
1716 mTotalEffectsMemory += desc->memoryUsage;
1717 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1718 desc->name, io, strategy, session, id);
1719 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1720
Eric Laurent1f2f2232014-06-02 12:01:23 -07001721 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1722 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1723 effectDesc->mIo = io;
1724 effectDesc->mStrategy = (routing_strategy)strategy;
1725 effectDesc->mSession = session;
1726 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001727
Eric Laurent1f2f2232014-06-02 12:01:23 -07001728 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001729
1730 return NO_ERROR;
1731}
1732
Eric Laurente0720872014-03-11 09:30:41 -07001733status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001734{
1735 ssize_t index = mEffects.indexOfKey(id);
1736 if (index < 0) {
1737 ALOGW("unregisterEffect() unknown effect ID %d", id);
1738 return INVALID_OPERATION;
1739 }
1740
Eric Laurent1f2f2232014-06-02 12:01:23 -07001741 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001742
Eric Laurent1f2f2232014-06-02 12:01:23 -07001743 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001744
Eric Laurent1f2f2232014-06-02 12:01:23 -07001745 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001746 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001747 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1748 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001749 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001750 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001751 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001752 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001753
1754 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001755
1756 return NO_ERROR;
1757}
1758
Eric Laurente0720872014-03-11 09:30:41 -07001759status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001760{
1761 ssize_t index = mEffects.indexOfKey(id);
1762 if (index < 0) {
1763 ALOGW("unregisterEffect() unknown effect ID %d", id);
1764 return INVALID_OPERATION;
1765 }
1766
1767 return setEffectEnabled(mEffects.valueAt(index), enabled);
1768}
1769
Eric Laurent1f2f2232014-06-02 12:01:23 -07001770status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001771{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001772 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001773 ALOGV("setEffectEnabled(%s) effect already %s",
1774 enabled?"true":"false", enabled?"enabled":"disabled");
1775 return INVALID_OPERATION;
1776 }
1777
1778 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001779 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001780 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001781 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001782 return INVALID_OPERATION;
1783 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001784 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001785 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1786 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001787 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001788 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001789 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1790 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001791 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001792 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001793 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1794 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001795 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001796 return NO_ERROR;
1797}
1798
Eric Laurente0720872014-03-11 09:30:41 -07001799bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001800{
1801 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001802 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1803 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1804 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001805 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001806 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001807 return true;
1808 }
1809 }
1810 return false;
1811}
1812
Eric Laurente0720872014-03-11 09:30:41 -07001813bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001814{
1815 nsecs_t sysTime = systemTime();
1816 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001817 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001818 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001819 return true;
1820 }
1821 }
1822 return false;
1823}
1824
Eric Laurente0720872014-03-11 09:30:41 -07001825bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001826 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001827{
1828 nsecs_t sysTime = systemTime();
1829 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001830 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001831 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001832 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001833 return true;
1834 }
1835 }
1836 return false;
1837}
1838
Eric Laurente0720872014-03-11 09:30:41 -07001839bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001840{
1841 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001842 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001843 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001844 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001845 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1846 && (inputDescriptor->mRefCount > 0)) {
1847 return true;
1848 }
1849 }
1850 return false;
1851}
1852
1853
Eric Laurente0720872014-03-11 09:30:41 -07001854status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001855{
1856 const size_t SIZE = 256;
1857 char buffer[SIZE];
1858 String8 result;
1859
1860 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1861 result.append(buffer);
1862
1863 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1864 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001865 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1866 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001867 snprintf(buffer, SIZE, " Force use for communications %d\n",
1868 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001869 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001870 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001871 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001872 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001873 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001874 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001875 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001876 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001877 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001878 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1879 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1880 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001881
Eric Laurent3a4311c2014-03-17 12:00:47 -07001882 snprintf(buffer, SIZE, " Available output devices:\n");
1883 result.append(buffer);
1884 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001885 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001886 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001887 }
1888 snprintf(buffer, SIZE, "\n Available input devices:\n");
1889 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001890 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001891 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001892 }
Eric Laurente552edb2014-03-10 17:42:56 -07001893
1894 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1895 write(fd, buffer, strlen(buffer));
1896 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001897 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001898 write(fd, buffer, strlen(buffer));
1899 mHwModules[i]->dump(fd);
1900 }
1901
1902 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1903 write(fd, buffer, strlen(buffer));
1904 for (size_t i = 0; i < mOutputs.size(); i++) {
1905 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1906 write(fd, buffer, strlen(buffer));
1907 mOutputs.valueAt(i)->dump(fd);
1908 }
1909
1910 snprintf(buffer, SIZE, "\nInputs dump:\n");
1911 write(fd, buffer, strlen(buffer));
1912 for (size_t i = 0; i < mInputs.size(); i++) {
1913 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1914 write(fd, buffer, strlen(buffer));
1915 mInputs.valueAt(i)->dump(fd);
1916 }
1917
1918 snprintf(buffer, SIZE, "\nStreams dump:\n");
1919 write(fd, buffer, strlen(buffer));
1920 snprintf(buffer, SIZE,
1921 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1922 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001923 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001924 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001925 write(fd, buffer, strlen(buffer));
1926 mStreams[i].dump(fd);
1927 }
1928
1929 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1930 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1931 write(fd, buffer, strlen(buffer));
1932
1933 snprintf(buffer, SIZE, "Registered effects:\n");
1934 write(fd, buffer, strlen(buffer));
1935 for (size_t i = 0; i < mEffects.size(); i++) {
1936 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1937 write(fd, buffer, strlen(buffer));
1938 mEffects.valueAt(i)->dump(fd);
1939 }
1940
Eric Laurent4d416952014-08-10 14:07:09 -07001941 snprintf(buffer, SIZE, "\nAudio Patches:\n");
1942 write(fd, buffer, strlen(buffer));
1943 for (size_t i = 0; i < mAudioPatches.size(); i++) {
1944 mAudioPatches[i]->dump(fd, 2, i);
1945 }
Eric Laurente552edb2014-03-10 17:42:56 -07001946
1947 return NO_ERROR;
1948}
1949
1950// This function checks for the parameters which can be offloaded.
1951// This can be enhanced depending on the capability of the DSP and policy
1952// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001953bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001954{
1955 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001956 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001957 offloadInfo.sample_rate, offloadInfo.channel_mask,
1958 offloadInfo.format,
1959 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1960 offloadInfo.has_video);
1961
1962 // Check if offload has been disabled
1963 char propValue[PROPERTY_VALUE_MAX];
1964 if (property_get("audio.offload.disable", propValue, "0")) {
1965 if (atoi(propValue) != 0) {
1966 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1967 return false;
1968 }
1969 }
1970
1971 // Check if stream type is music, then only allow offload as of now.
1972 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1973 {
1974 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1975 return false;
1976 }
1977
1978 //TODO: enable audio offloading with video when ready
1979 if (offloadInfo.has_video)
1980 {
1981 ALOGV("isOffloadSupported: has_video == true, returning false");
1982 return false;
1983 }
1984
1985 //If duration is less than minimum value defined in property, return false
1986 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1987 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1988 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1989 return false;
1990 }
1991 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1992 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1993 return false;
1994 }
1995
1996 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1997 // creating an offloaded track and tearing it down immediately after start when audioflinger
1998 // detects there is an active non offloadable effect.
1999 // FIXME: We should check the audio session here but we do not have it in this context.
2000 // This may prevent offloading in rare situations where effects are left active by apps
2001 // in the background.
2002 if (isNonOffloadableEffectEnabled()) {
2003 return false;
2004 }
2005
2006 // See if there is a profile to support this.
2007 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002008 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002009 offloadInfo.sample_rate,
2010 offloadInfo.format,
2011 offloadInfo.channel_mask,
2012 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002013 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2014 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002015}
2016
Eric Laurent6a94d692014-05-20 11:18:06 -07002017status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2018 audio_port_type_t type,
2019 unsigned int *num_ports,
2020 struct audio_port *ports,
2021 unsigned int *generation)
2022{
2023 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2024 generation == NULL) {
2025 return BAD_VALUE;
2026 }
2027 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2028 if (ports == NULL) {
2029 *num_ports = 0;
2030 }
2031
2032 size_t portsWritten = 0;
2033 size_t portsMax = *num_ports;
2034 *num_ports = 0;
2035 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2036 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2037 for (size_t i = 0;
2038 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2039 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2040 }
2041 *num_ports += mAvailableOutputDevices.size();
2042 }
2043 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2044 for (size_t i = 0;
2045 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2046 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2047 }
2048 *num_ports += mAvailableInputDevices.size();
2049 }
2050 }
2051 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2052 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2053 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2054 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2055 }
2056 *num_ports += mInputs.size();
2057 }
2058 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002059 size_t numOutputs = 0;
2060 for (size_t i = 0; i < mOutputs.size(); i++) {
2061 if (!mOutputs[i]->isDuplicated()) {
2062 numOutputs++;
2063 if (portsWritten < portsMax) {
2064 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2065 }
2066 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002067 }
Eric Laurent84c70242014-06-23 08:46:27 -07002068 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002069 }
2070 }
2071 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002072 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002073 return NO_ERROR;
2074}
2075
2076status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2077{
2078 return NO_ERROR;
2079}
2080
Eric Laurent1f2f2232014-06-02 12:01:23 -07002081sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002082 audio_port_handle_t id) const
2083{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002084 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002085 for (size_t i = 0; i < mOutputs.size(); i++) {
2086 outputDesc = mOutputs.valueAt(i);
2087 if (outputDesc->mId == id) {
2088 break;
2089 }
2090 }
2091 return outputDesc;
2092}
2093
Eric Laurent1f2f2232014-06-02 12:01:23 -07002094sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002095 audio_port_handle_t id) const
2096{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002097 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002098 for (size_t i = 0; i < mInputs.size(); i++) {
2099 inputDesc = mInputs.valueAt(i);
2100 if (inputDesc->mId == id) {
2101 break;
2102 }
2103 }
2104 return inputDesc;
2105}
2106
Eric Laurent1f2f2232014-06-02 12:01:23 -07002107sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2108 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002109{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002110 sp <HwModule> module;
2111
Eric Laurent6a94d692014-05-20 11:18:06 -07002112 for (size_t i = 0; i < mHwModules.size(); i++) {
2113 if (mHwModules[i]->mHandle == 0) {
2114 continue;
2115 }
2116 if (audio_is_output_device(device)) {
2117 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2118 {
2119 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2120 return mHwModules[i];
2121 }
2122 }
2123 } else {
2124 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2125 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2126 device & ~AUDIO_DEVICE_BIT_IN) {
2127 return mHwModules[i];
2128 }
2129 }
2130 }
2131 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002132 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002133}
2134
Eric Laurent1f2f2232014-06-02 12:01:23 -07002135sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002136{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002137 sp <HwModule> module;
2138
Eric Laurent1afeecb2014-05-14 08:52:28 -07002139 for (size_t i = 0; i < mHwModules.size(); i++)
2140 {
2141 if (strcmp(mHwModules[i]->mName, name) == 0) {
2142 return mHwModules[i];
2143 }
2144 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002145 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002146}
2147
Eric Laurentc2730ba2014-07-20 15:47:07 -07002148audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2149{
2150 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2151 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2152 return devices & mAvailableOutputDevices.types();
2153}
2154
2155audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2156{
2157 audio_module_handle_t primaryHandle =
2158 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2159 audio_devices_t devices = AUDIO_DEVICE_NONE;
2160 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2161 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2162 devices |= mAvailableInputDevices[i]->mDeviceType;
2163 }
2164 }
2165 return devices;
2166}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002167
Eric Laurent6a94d692014-05-20 11:18:06 -07002168status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2169 audio_patch_handle_t *handle,
2170 uid_t uid)
2171{
2172 ALOGV("createAudioPatch()");
2173
2174 if (handle == NULL || patch == NULL) {
2175 return BAD_VALUE;
2176 }
2177 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2178
Eric Laurent874c42872014-08-08 15:13:39 -07002179 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2180 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2181 return BAD_VALUE;
2182 }
2183 // only one source per audio patch supported for now
2184 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002185 return INVALID_OPERATION;
2186 }
Eric Laurent874c42872014-08-08 15:13:39 -07002187
2188 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002189 return INVALID_OPERATION;
2190 }
Eric Laurent874c42872014-08-08 15:13:39 -07002191 for (size_t i = 0; i < patch->num_sinks; i++) {
2192 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2193 return INVALID_OPERATION;
2194 }
2195 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002196
2197 sp<AudioPatch> patchDesc;
2198 ssize_t index = mAudioPatches.indexOfKey(*handle);
2199
Eric Laurent6a94d692014-05-20 11:18:06 -07002200 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2201 patch->sources[0].role,
2202 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002203#if LOG_NDEBUG == 0
2204 for (size_t i = 0; i < patch->num_sinks; i++) {
2205 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2206 patch->sinks[i].role,
2207 patch->sinks[i].type);
2208 }
2209#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002210
2211 if (index >= 0) {
2212 patchDesc = mAudioPatches.valueAt(index);
2213 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2214 mUidCached, patchDesc->mUid, uid);
2215 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2216 return INVALID_OPERATION;
2217 }
2218 } else {
2219 *handle = 0;
2220 }
2221
2222 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002223 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002224 if (outputDesc == NULL) {
2225 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2226 return BAD_VALUE;
2227 }
Eric Laurent84c70242014-06-23 08:46:27 -07002228 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2229 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002230 if (patchDesc != 0) {
2231 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2232 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2233 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2234 return BAD_VALUE;
2235 }
2236 }
Eric Laurent874c42872014-08-08 15:13:39 -07002237 DeviceVector devices;
2238 for (size_t i = 0; i < patch->num_sinks; i++) {
2239 // Only support mix to devices connection
2240 // TODO add support for mix to mix connection
2241 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2242 ALOGV("createAudioPatch() source mix but sink is not a device");
2243 return INVALID_OPERATION;
2244 }
2245 sp<DeviceDescriptor> devDesc =
2246 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2247 if (devDesc == 0) {
2248 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2249 return BAD_VALUE;
2250 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002251
Eric Laurent874c42872014-08-08 15:13:39 -07002252 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2253 patch->sources[0].sample_rate,
2254 NULL, // updatedSamplingRate
2255 patch->sources[0].format,
2256 patch->sources[0].channel_mask,
2257 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2258 ALOGV("createAudioPatch() profile not supported for device %08x",
2259 devDesc->mDeviceType);
2260 return INVALID_OPERATION;
2261 }
2262 devices.add(devDesc);
2263 }
2264 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002265 return INVALID_OPERATION;
2266 }
Eric Laurent874c42872014-08-08 15:13:39 -07002267
Eric Laurent6a94d692014-05-20 11:18:06 -07002268 // TODO: reconfigure output format and channels here
2269 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002270 devices.types(), outputDesc->mIoHandle);
2271 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002272 index = mAudioPatches.indexOfKey(*handle);
2273 if (index >= 0) {
2274 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2275 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2276 }
2277 patchDesc = mAudioPatches.valueAt(index);
2278 patchDesc->mUid = uid;
2279 ALOGV("createAudioPatch() success");
2280 } else {
2281 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2282 return INVALID_OPERATION;
2283 }
2284 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2285 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2286 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002287 // only one sink supported when connecting an input device to a mix
2288 if (patch->num_sinks > 1) {
2289 return INVALID_OPERATION;
2290 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002291 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002292 if (inputDesc == NULL) {
2293 return BAD_VALUE;
2294 }
2295 if (patchDesc != 0) {
2296 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2297 return BAD_VALUE;
2298 }
2299 }
2300 sp<DeviceDescriptor> devDesc =
2301 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2302 if (devDesc == 0) {
2303 return BAD_VALUE;
2304 }
2305
Eric Laurent84c70242014-06-23 08:46:27 -07002306 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002307 patch->sinks[0].sample_rate,
2308 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002309 patch->sinks[0].format,
2310 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002311 // FIXME for the parameter type,
2312 // and the NONE
2313 (audio_output_flags_t)
2314 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002315 return INVALID_OPERATION;
2316 }
2317 // TODO: reconfigure output format and channels here
2318 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002319 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002320 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002321 index = mAudioPatches.indexOfKey(*handle);
2322 if (index >= 0) {
2323 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2324 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2325 }
2326 patchDesc = mAudioPatches.valueAt(index);
2327 patchDesc->mUid = uid;
2328 ALOGV("createAudioPatch() success");
2329 } else {
2330 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2331 return INVALID_OPERATION;
2332 }
2333 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2334 // device to device connection
2335 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002336 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002337 return BAD_VALUE;
2338 }
2339 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002340 sp<DeviceDescriptor> srcDeviceDesc =
2341 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002342 if (srcDeviceDesc == 0) {
2343 return BAD_VALUE;
2344 }
Eric Laurent874c42872014-08-08 15:13:39 -07002345
Eric Laurent6a94d692014-05-20 11:18:06 -07002346 //update source and sink with our own data as the data passed in the patch may
2347 // be incomplete.
2348 struct audio_patch newPatch = *patch;
2349 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002350
Eric Laurent874c42872014-08-08 15:13:39 -07002351 for (size_t i = 0; i < patch->num_sinks; i++) {
2352 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2353 ALOGV("createAudioPatch() source device but one sink is not a device");
2354 return INVALID_OPERATION;
2355 }
2356
2357 sp<DeviceDescriptor> sinkDeviceDesc =
2358 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2359 if (sinkDeviceDesc == 0) {
2360 return BAD_VALUE;
2361 }
2362 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2363
2364 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2365 // only one sink supported when connected devices across HW modules
2366 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002367 return INVALID_OPERATION;
2368 }
Eric Laurent874c42872014-08-08 15:13:39 -07002369 SortedVector<audio_io_handle_t> outputs =
2370 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2371 mOutputs);
2372 // if the sink device is reachable via an opened output stream, request to go via
2373 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002374 audio_io_handle_t output = selectOutput(outputs,
2375 AUDIO_OUTPUT_FLAG_NONE,
2376 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002377 if (output != AUDIO_IO_HANDLE_NONE) {
2378 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2379 if (outputDesc->isDuplicated()) {
2380 return INVALID_OPERATION;
2381 }
2382 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2383 newPatch.num_sources = 2;
2384 }
Eric Laurent83b88082014-06-20 18:31:16 -07002385 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002386 }
2387 // TODO: check from routing capabilities in config file and other conflicting patches
2388
2389 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2390 if (index >= 0) {
2391 afPatchHandle = patchDesc->mAfPatchHandle;
2392 }
2393
2394 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2395 &afPatchHandle,
2396 0);
2397 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2398 status, afPatchHandle);
2399 if (status == NO_ERROR) {
2400 if (index < 0) {
2401 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2402 &newPatch, uid);
2403 addAudioPatch(patchDesc->mHandle, patchDesc);
2404 } else {
2405 patchDesc->mPatch = newPatch;
2406 }
2407 patchDesc->mAfPatchHandle = afPatchHandle;
2408 *handle = patchDesc->mHandle;
2409 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002410 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002411 } else {
2412 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2413 status);
2414 return INVALID_OPERATION;
2415 }
2416 } else {
2417 return BAD_VALUE;
2418 }
2419 } else {
2420 return BAD_VALUE;
2421 }
2422 return NO_ERROR;
2423}
2424
2425status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2426 uid_t uid)
2427{
2428 ALOGV("releaseAudioPatch() patch %d", handle);
2429
2430 ssize_t index = mAudioPatches.indexOfKey(handle);
2431
2432 if (index < 0) {
2433 return BAD_VALUE;
2434 }
2435 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2436 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2437 mUidCached, patchDesc->mUid, uid);
2438 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2439 return INVALID_OPERATION;
2440 }
2441
2442 struct audio_patch *patch = &patchDesc->mPatch;
2443 patchDesc->mUid = mUidCached;
2444 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002445 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002446 if (outputDesc == NULL) {
2447 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2448 return BAD_VALUE;
2449 }
2450
2451 setOutputDevice(outputDesc->mIoHandle,
2452 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2453 true,
2454 0,
2455 NULL);
2456 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2457 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002458 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002459 if (inputDesc == NULL) {
2460 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2461 return BAD_VALUE;
2462 }
2463 setInputDevice(inputDesc->mIoHandle,
2464 getNewInputDevice(inputDesc->mIoHandle),
2465 true,
2466 NULL);
2467 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2468 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2469 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2470 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2471 status, patchDesc->mAfPatchHandle);
2472 removeAudioPatch(patchDesc->mHandle);
2473 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002474 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002475 } else {
2476 return BAD_VALUE;
2477 }
2478 } else {
2479 return BAD_VALUE;
2480 }
2481 return NO_ERROR;
2482}
2483
2484status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2485 struct audio_patch *patches,
2486 unsigned int *generation)
2487{
2488 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2489 generation == NULL) {
2490 return BAD_VALUE;
2491 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002492 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002493 *num_patches, patches, mAudioPatches.size());
2494 if (patches == NULL) {
2495 *num_patches = 0;
2496 }
2497
2498 size_t patchesWritten = 0;
2499 size_t patchesMax = *num_patches;
2500 for (size_t i = 0;
2501 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2502 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2503 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002504 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002505 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2506 }
2507 *num_patches = mAudioPatches.size();
2508
2509 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002510 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002511 return NO_ERROR;
2512}
2513
Eric Laurente1715a42014-05-20 11:30:42 -07002514status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002515{
Eric Laurente1715a42014-05-20 11:30:42 -07002516 ALOGV("setAudioPortConfig()");
2517
2518 if (config == NULL) {
2519 return BAD_VALUE;
2520 }
2521 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2522 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002523 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2524 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002525 }
2526
Eric Laurenta121f902014-06-03 13:32:54 -07002527 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002528 if (config->type == AUDIO_PORT_TYPE_MIX) {
2529 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002530 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002531 if (outputDesc == NULL) {
2532 return BAD_VALUE;
2533 }
Eric Laurent84c70242014-06-23 08:46:27 -07002534 ALOG_ASSERT(!outputDesc->isDuplicated(),
2535 "setAudioPortConfig() called on duplicated output %d",
2536 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002537 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002538 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002539 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002540 if (inputDesc == NULL) {
2541 return BAD_VALUE;
2542 }
Eric Laurenta121f902014-06-03 13:32:54 -07002543 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002544 } else {
2545 return BAD_VALUE;
2546 }
2547 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2548 sp<DeviceDescriptor> deviceDesc;
2549 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2550 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2551 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2552 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2553 } else {
2554 return BAD_VALUE;
2555 }
2556 if (deviceDesc == NULL) {
2557 return BAD_VALUE;
2558 }
Eric Laurenta121f902014-06-03 13:32:54 -07002559 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002560 } else {
2561 return BAD_VALUE;
2562 }
2563
Eric Laurenta121f902014-06-03 13:32:54 -07002564 struct audio_port_config backupConfig;
2565 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2566 if (status == NO_ERROR) {
2567 struct audio_port_config newConfig;
2568 audioPortConfig->toAudioPortConfig(&newConfig, config);
2569 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002570 }
Eric Laurenta121f902014-06-03 13:32:54 -07002571 if (status != NO_ERROR) {
2572 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002573 }
Eric Laurente1715a42014-05-20 11:30:42 -07002574
2575 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002576}
2577
2578void AudioPolicyManager::clearAudioPatches(uid_t uid)
2579{
2580 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2581 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2582 if (patchDesc->mUid == uid) {
2583 // releaseAudioPatch() removes the patch from mAudioPatches
2584 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2585 i--;
2586 }
2587 }
2588 }
2589}
2590
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002591status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2592 audio_io_handle_t *ioHandle,
2593 audio_devices_t *device)
2594{
2595 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2596 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2597 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2598
2599 mSoundTriggerSessions.add(*session, *ioHandle);
2600
2601 return NO_ERROR;
2602}
2603
2604status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2605{
2606 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2607 if (index < 0) {
2608 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2609 return BAD_VALUE;
2610 }
2611
2612 mSoundTriggerSessions.removeItem(session);
2613 return NO_ERROR;
2614}
2615
Eric Laurent6a94d692014-05-20 11:18:06 -07002616status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2617 const sp<AudioPatch>& patch)
2618{
2619 ssize_t index = mAudioPatches.indexOfKey(handle);
2620
2621 if (index >= 0) {
2622 ALOGW("addAudioPatch() patch %d already in", handle);
2623 return ALREADY_EXISTS;
2624 }
2625 mAudioPatches.add(handle, patch);
2626 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2627 "sink handle %d",
2628 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2629 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2630 return NO_ERROR;
2631}
2632
2633status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2634{
2635 ssize_t index = mAudioPatches.indexOfKey(handle);
2636
2637 if (index < 0) {
2638 ALOGW("removeAudioPatch() patch %d not in", handle);
2639 return ALREADY_EXISTS;
2640 }
2641 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2642 mAudioPatches.valueAt(index)->mAfPatchHandle);
2643 mAudioPatches.removeItemsAt(index);
2644 return NO_ERROR;
2645}
2646
Eric Laurente552edb2014-03-10 17:42:56 -07002647// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002648// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002649// ----------------------------------------------------------------------------
2650
Eric Laurent3a4311c2014-03-17 12:00:47 -07002651uint32_t AudioPolicyManager::nextUniqueId()
2652{
2653 return android_atomic_inc(&mNextUniqueId);
2654}
2655
Eric Laurent6a94d692014-05-20 11:18:06 -07002656uint32_t AudioPolicyManager::nextAudioPortGeneration()
2657{
2658 return android_atomic_inc(&mAudioPortGeneration);
2659}
2660
Eric Laurente0720872014-03-11 09:30:41 -07002661AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002662 :
2663#ifdef AUDIO_POLICY_TEST
2664 Thread(false),
2665#endif //AUDIO_POLICY_TEST
2666 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002667 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002668 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2669 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002670 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002671 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Vineeta Srivastavaf2ab2192014-10-11 21:59:36 +00002672 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002673{
Eric Laurent6a94d692014-05-20 11:18:06 -07002674 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002675 mpClientInterface = clientInterface;
2676
Eric Laurent3b73df72014-03-11 09:06:29 -07002677 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2678 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002679 }
2680
Eric Laurent1afeecb2014-05-14 08:52:28 -07002681 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002682 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2683 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2684 ALOGE("could not load audio policy configuration file, setting defaults");
2685 defaultAudioPolicyConfig();
2686 }
2687 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002688 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002689
2690 // must be done after reading the policy
2691 initializeVolumeCurves();
2692
2693 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002694 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2695 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002696 for (size_t i = 0; i < mHwModules.size(); i++) {
2697 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2698 if (mHwModules[i]->mHandle == 0) {
2699 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2700 continue;
2701 }
2702 // open all output streams needed to access attached devices
2703 // except for direct output streams that are only opened when they are actually
2704 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002705 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002706 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2707 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002708 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002709
Eric Laurent3a4311c2014-03-17 12:00:47 -07002710 if (outProfile->mSupportedDevices.isEmpty()) {
2711 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2712 continue;
2713 }
2714
Eric Laurentd78f1532014-09-16 16:38:20 -07002715 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
2716 continue;
2717 }
Eric Laurent83b88082014-06-20 18:31:16 -07002718 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2719 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2720 profileType = mDefaultOutputDevice->mDeviceType;
2721 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07002722 // chose first device present in mSupportedDevices also part of
2723 // outputDeviceTypes
2724 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2725 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
2726 if ((profileType & outputDeviceTypes) != 0) {
2727 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002728 }
Eric Laurente552edb2014-03-10 17:42:56 -07002729 }
2730 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002731 if ((profileType & outputDeviceTypes) == 0) {
2732 continue;
2733 }
2734 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
2735
2736 outputDesc->mDevice = profileType;
2737 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2738 config.sample_rate = outputDesc->mSamplingRate;
2739 config.channel_mask = outputDesc->mChannelMask;
2740 config.format = outputDesc->mFormat;
2741 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2742 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2743 &output,
2744 &config,
2745 &outputDesc->mDevice,
2746 String8(""),
2747 &outputDesc->mLatency,
2748 outputDesc->mFlags);
2749
2750 if (status != NO_ERROR) {
2751 ALOGW("Cannot open output stream for device %08x on hw module %s",
2752 outputDesc->mDevice,
2753 mHwModules[i]->mName);
2754 } else {
2755 outputDesc->mSamplingRate = config.sample_rate;
2756 outputDesc->mChannelMask = config.channel_mask;
2757 outputDesc->mFormat = config.format;
2758
2759 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2760 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
2761 ssize_t index =
2762 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2763 // give a valid ID to an attached device once confirmed it is reachable
2764 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2765 mAvailableOutputDevices[index]->mId = nextUniqueId();
2766 mAvailableOutputDevices[index]->mModule = mHwModules[i];
2767 }
2768 }
2769 if (mPrimaryOutput == 0 &&
2770 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2771 mPrimaryOutput = output;
2772 }
2773 addOutput(output, outputDesc);
2774 setOutputDevice(output,
2775 outputDesc->mDevice,
2776 true);
2777 }
Eric Laurente552edb2014-03-10 17:42:56 -07002778 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002779 // open input streams needed to access attached devices to validate
2780 // mAvailableInputDevices list
2781 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2782 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002783 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002784
Eric Laurent3a4311c2014-03-17 12:00:47 -07002785 if (inProfile->mSupportedDevices.isEmpty()) {
2786 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2787 continue;
2788 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002789 // chose first device present in mSupportedDevices also part of
2790 // inputDeviceTypes
2791 audio_devices_t profileType = AUDIO_DEVICE_NONE;
2792 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2793 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
2794 if (profileType & inputDeviceTypes) {
2795 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002796 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002797 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002798 if ((profileType & inputDeviceTypes) == 0) {
2799 continue;
2800 }
2801 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2802
2803 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2804 inputDesc->mDevice = profileType;
2805
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002806 // find the address
2807 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
2808 // the inputs vector must be of size 1, but we don't want to crash here
2809 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
2810 : String8("");
2811 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
2812 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
2813
Eric Laurentd78f1532014-09-16 16:38:20 -07002814 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2815 config.sample_rate = inputDesc->mSamplingRate;
2816 config.channel_mask = inputDesc->mChannelMask;
2817 config.format = inputDesc->mFormat;
2818 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2819 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2820 &input,
2821 &config,
2822 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002823 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07002824 AUDIO_SOURCE_MIC,
2825 AUDIO_INPUT_FLAG_NONE);
2826
2827 if (status == NO_ERROR) {
2828 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2829 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
2830 ssize_t index =
2831 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2832 // give a valid ID to an attached device once confirmed it is reachable
2833 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2834 mAvailableInputDevices[index]->mId = nextUniqueId();
2835 mAvailableInputDevices[index]->mModule = mHwModules[i];
2836 }
2837 }
2838 mpClientInterface->closeInput(input);
2839 } else {
2840 ALOGW("Cannot open input stream for device %08x on hw module %s",
2841 inputDesc->mDevice,
2842 mHwModules[i]->mName);
2843 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002844 }
2845 }
2846 // make sure all attached devices have been allocated a unique ID
2847 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2848 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002849 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002850 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2851 continue;
2852 }
2853 i++;
2854 }
2855 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2856 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002857 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002858 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2859 continue;
2860 }
2861 i++;
2862 }
2863 // make sure default device is reachable
2864 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002865 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002866 }
Eric Laurente552edb2014-03-10 17:42:56 -07002867
2868 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2869
2870 updateDevicesAndOutputs();
2871
2872#ifdef AUDIO_POLICY_TEST
2873 if (mPrimaryOutput != 0) {
2874 AudioParameter outputCmd = AudioParameter();
2875 outputCmd.addInt(String8("set_id"), 0);
2876 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2877
2878 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2879 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002880 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2881 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002882 mTestLatencyMs = 0;
2883 mCurOutput = 0;
2884 mDirectOutput = false;
2885 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2886 mTestOutputs[i] = 0;
2887 }
2888
2889 const size_t SIZE = 256;
2890 char buffer[SIZE];
2891 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2892 run(buffer, ANDROID_PRIORITY_AUDIO);
2893 }
2894#endif //AUDIO_POLICY_TEST
2895}
2896
Eric Laurente0720872014-03-11 09:30:41 -07002897AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002898{
2899#ifdef AUDIO_POLICY_TEST
2900 exit();
2901#endif //AUDIO_POLICY_TEST
2902 for (size_t i = 0; i < mOutputs.size(); i++) {
2903 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002904 }
2905 for (size_t i = 0; i < mInputs.size(); i++) {
2906 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002907 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002908 mAvailableOutputDevices.clear();
2909 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002910 mOutputs.clear();
2911 mInputs.clear();
2912 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002913}
2914
Eric Laurente0720872014-03-11 09:30:41 -07002915status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002916{
2917 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2918}
2919
2920#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002921bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002922{
2923 ALOGV("entering threadLoop()");
2924 while (!exitPending())
2925 {
2926 String8 command;
2927 int valueInt;
2928 String8 value;
2929
2930 Mutex::Autolock _l(mLock);
2931 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2932
2933 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2934 AudioParameter param = AudioParameter(command);
2935
2936 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2937 valueInt != 0) {
2938 ALOGV("Test command %s received", command.string());
2939 String8 target;
2940 if (param.get(String8("target"), target) != NO_ERROR) {
2941 target = "Manager";
2942 }
2943 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2944 param.remove(String8("test_cmd_policy_output"));
2945 mCurOutput = valueInt;
2946 }
2947 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2948 param.remove(String8("test_cmd_policy_direct"));
2949 if (value == "false") {
2950 mDirectOutput = false;
2951 } else if (value == "true") {
2952 mDirectOutput = true;
2953 }
2954 }
2955 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2956 param.remove(String8("test_cmd_policy_input"));
2957 mTestInput = valueInt;
2958 }
2959
2960 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2961 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002962 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002963 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002964 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002965 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002966 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002967 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002968 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002969 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002970 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002971 if (target == "Manager") {
2972 mTestFormat = format;
2973 } else if (mTestOutputs[mCurOutput] != 0) {
2974 AudioParameter outputParam = AudioParameter();
2975 outputParam.addInt(String8("format"), format);
2976 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2977 }
2978 }
2979 }
2980 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2981 param.remove(String8("test_cmd_policy_channels"));
2982 int channels = 0;
2983
2984 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002985 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002986 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002987 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002988 }
2989 if (channels != 0) {
2990 if (target == "Manager") {
2991 mTestChannels = channels;
2992 } else if (mTestOutputs[mCurOutput] != 0) {
2993 AudioParameter outputParam = AudioParameter();
2994 outputParam.addInt(String8("channels"), channels);
2995 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2996 }
2997 }
2998 }
2999 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3000 param.remove(String8("test_cmd_policy_sampleRate"));
3001 if (valueInt >= 0 && valueInt <= 96000) {
3002 int samplingRate = valueInt;
3003 if (target == "Manager") {
3004 mTestSamplingRate = samplingRate;
3005 } else if (mTestOutputs[mCurOutput] != 0) {
3006 AudioParameter outputParam = AudioParameter();
3007 outputParam.addInt(String8("sampling_rate"), samplingRate);
3008 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3009 }
3010 }
3011 }
3012
3013 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3014 param.remove(String8("test_cmd_policy_reopen"));
3015
Eric Laurent1f2f2232014-06-02 12:01:23 -07003016 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003017 mpClientInterface->closeOutput(mPrimaryOutput);
3018
3019 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3020
Eric Laurente552edb2014-03-10 17:42:56 -07003021 mOutputs.removeItem(mPrimaryOutput);
3022
Eric Laurent1f2f2232014-06-02 12:01:23 -07003023 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003024 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003025 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3026 config.sample_rate = outputDesc->mSamplingRate;
3027 config.channel_mask = outputDesc->mChannelMask;
3028 config.format = outputDesc->mFormat;
3029 status_t status = mpClientInterface->openOutput(moduleHandle,
3030 &mPrimaryOutput,
3031 &config,
3032 &outputDesc->mDevice,
3033 String8(""),
3034 &outputDesc->mLatency,
3035 outputDesc->mFlags);
3036 if (status != NO_ERROR) {
3037 ALOGE("Failed to reopen hardware output stream, "
3038 "samplingRate: %d, format %d, channels %d",
3039 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003040 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003041 outputDesc->mSamplingRate = config.sample_rate;
3042 outputDesc->mChannelMask = config.channel_mask;
3043 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003044 AudioParameter outputCmd = AudioParameter();
3045 outputCmd.addInt(String8("set_id"), 0);
3046 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3047 addOutput(mPrimaryOutput, outputDesc);
3048 }
3049 }
3050
3051
3052 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3053 }
3054 }
3055 return false;
3056}
3057
Eric Laurente0720872014-03-11 09:30:41 -07003058void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003059{
3060 {
3061 AutoMutex _l(mLock);
3062 requestExit();
3063 mWaitWorkCV.signal();
3064 }
3065 requestExitAndWait();
3066}
3067
Eric Laurente0720872014-03-11 09:30:41 -07003068int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003069{
3070 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3071 if (output == mTestOutputs[i]) return i;
3072 }
3073 return 0;
3074}
3075#endif //AUDIO_POLICY_TEST
3076
3077// ---
3078
Eric Laurent1f2f2232014-06-02 12:01:23 -07003079void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003080{
Eric Laurent1c333e22014-05-20 10:48:17 -07003081 outputDesc->mIoHandle = output;
3082 outputDesc->mId = nextUniqueId();
3083 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003084 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003085}
3086
Eric Laurent1f2f2232014-06-02 12:01:23 -07003087void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003088{
Eric Laurent1c333e22014-05-20 10:48:17 -07003089 inputDesc->mIoHandle = input;
3090 inputDesc->mId = nextUniqueId();
3091 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003092 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003093}
Eric Laurente552edb2014-03-10 17:42:56 -07003094
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003095void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3096 const String8 address /*in*/,
3097 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3098 // look for a match on the given address on the addresses of the outputs:
3099 // find the address by finding the patch that maps to this output
3100 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3101 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3102 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3103 if (patchIdx >= 0) {
3104 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3105 const int numSinks = patchDesc->mPatch.num_sinks;
3106 for (ssize_t j=0; j < numSinks; j++) {
3107 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3108 const char* patchAddr =
3109 patchDesc->mPatch.sinks[j].ext.device.address;
3110 if (strncmp(patchAddr,
3111 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003112 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003113 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3114 outputs.add(desc->mIoHandle);
3115 break;
3116 }
3117 }
3118 }
3119 }
3120}
3121
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003122status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003123 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003124 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003125 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003126{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003127 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003128 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003129 // erase all current sample rates, formats and channel masks
3130 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003131
Eric Laurent3b73df72014-03-11 09:06:29 -07003132 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003133 // first list already open outputs that can be routed to this device
3134 for (size_t i = 0; i < mOutputs.size(); i++) {
3135 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003136 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003137 if (!deviceDistinguishesOnAddress(device)) {
3138 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3139 outputs.add(mOutputs.keyAt(i));
3140 } else {
3141 ALOGV(" checking address match due to device 0x%x", device);
3142 findIoHandlesByAddress(desc, address, outputs);
3143 }
Eric Laurente552edb2014-03-10 17:42:56 -07003144 }
3145 }
3146 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003147 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003148 for (size_t i = 0; i < mHwModules.size(); i++)
3149 {
3150 if (mHwModules[i]->mHandle == 0) {
3151 continue;
3152 }
3153 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3154 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003155 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003156 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003157 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3158 }
3159 }
3160 }
3161
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003162 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3163
Eric Laurente552edb2014-03-10 17:42:56 -07003164 if (profiles.isEmpty() && outputs.isEmpty()) {
3165 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3166 return BAD_VALUE;
3167 }
3168
3169 // open outputs for matching profiles if needed. Direct outputs are also opened to
3170 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3171 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003172 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003173
3174 // nothing to do if one output is already opened for this profile
3175 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003176 for (j = 0; j < outputs.size(); j++) {
3177 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003178 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003179 // matching profile: save the sample rates, format and channel masks supported
3180 // by the profile in our device descriptor
3181 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003182 break;
3183 }
3184 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003185 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003186 continue;
3187 }
3188
Eric Laurent83b88082014-06-20 18:31:16 -07003189 ALOGV("opening output for device %08x with params %s profile %p",
3190 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003191 desc = new AudioOutputDescriptor(profile);
3192 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003193 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3194 config.sample_rate = desc->mSamplingRate;
3195 config.channel_mask = desc->mChannelMask;
3196 config.format = desc->mFormat;
3197 config.offload_info.sample_rate = desc->mSamplingRate;
3198 config.offload_info.channel_mask = desc->mChannelMask;
3199 config.offload_info.format = desc->mFormat;
3200 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3201 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3202 &output,
3203 &config,
3204 &desc->mDevice,
3205 address,
3206 &desc->mLatency,
3207 desc->mFlags);
3208 if (status == NO_ERROR) {
3209 desc->mSamplingRate = config.sample_rate;
3210 desc->mChannelMask = config.channel_mask;
3211 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003212
Eric Laurentd4692962014-05-05 18:13:44 -07003213 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003214 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003215 char *param = audio_device_address_to_parameter(device, address);
3216 mpClientInterface->setParameters(output, String8(param));
3217 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003218 }
3219
Eric Laurentd4692962014-05-05 18:13:44 -07003220 // Here is where we step through and resolve any "dynamic" fields
3221 String8 reply;
3222 char *value;
3223 if (profile->mSamplingRates[0] == 0) {
3224 reply = mpClientInterface->getParameters(output,
3225 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003226 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003227 reply.string());
3228 value = strpbrk((char *)reply.string(), "=");
3229 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003230 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003231 }
Eric Laurentd4692962014-05-05 18:13:44 -07003232 }
3233 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3234 reply = mpClientInterface->getParameters(output,
3235 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003236 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003237 reply.string());
3238 value = strpbrk((char *)reply.string(), "=");
3239 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003240 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003241 }
Eric Laurentd4692962014-05-05 18:13:44 -07003242 }
3243 if (profile->mChannelMasks[0] == 0) {
3244 reply = mpClientInterface->getParameters(output,
3245 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003246 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003247 reply.string());
3248 value = strpbrk((char *)reply.string(), "=");
3249 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003250 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003251 }
Eric Laurentd4692962014-05-05 18:13:44 -07003252 }
3253 if (((profile->mSamplingRates[0] == 0) &&
3254 (profile->mSamplingRates.size() < 2)) ||
3255 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3256 (profile->mFormats.size() < 2)) ||
3257 ((profile->mChannelMasks[0] == 0) &&
3258 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003259 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003260 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003261 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003262 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3263 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003264 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003265 config.sample_rate = profile->pickSamplingRate();
3266 config.channel_mask = profile->pickChannelMask();
3267 config.format = profile->pickFormat();
3268 config.offload_info.sample_rate = config.sample_rate;
3269 config.offload_info.channel_mask = config.channel_mask;
3270 config.offload_info.format = config.format;
3271 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3272 &output,
3273 &config,
3274 &desc->mDevice,
3275 address,
3276 &desc->mLatency,
3277 desc->mFlags);
3278 if (status == NO_ERROR) {
3279 desc->mSamplingRate = config.sample_rate;
3280 desc->mChannelMask = config.channel_mask;
3281 desc->mFormat = config.format;
3282 } else {
3283 output = AUDIO_IO_HANDLE_NONE;
3284 }
Eric Laurentd4692962014-05-05 18:13:44 -07003285 }
3286
Eric Laurentcf2c0212014-07-25 16:20:43 -07003287 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003288 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003289 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003290 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003291
Eric Laurentd4692962014-05-05 18:13:44 -07003292 // set initial stream volume for device
3293 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003294
Eric Laurentd4692962014-05-05 18:13:44 -07003295 //TODO: configure audio effect output stage here
3296
3297 // open a duplicating output thread for the new output and the primary output
3298 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3299 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003300 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003301 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003302 sp<AudioOutputDescriptor> dupOutputDesc =
3303 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003304 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3305 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3306 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3307 dupOutputDesc->mFormat = desc->mFormat;
3308 dupOutputDesc->mChannelMask = desc->mChannelMask;
3309 dupOutputDesc->mLatency = desc->mLatency;
3310 addOutput(duplicatedOutput, dupOutputDesc);
3311 applyStreamVolumes(duplicatedOutput, device, 0, true);
3312 } else {
3313 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3314 mPrimaryOutput, output);
3315 mpClientInterface->closeOutput(output);
3316 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003317 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003318 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003319 }
Eric Laurente552edb2014-03-10 17:42:56 -07003320 }
3321 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003322 } else {
3323 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003324 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003325 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003326 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003327 profiles.removeAt(profile_index);
3328 profile_index--;
3329 } else {
3330 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003331 devDesc->importAudioPort(profile);
3332
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003333 if (deviceDistinguishesOnAddress(device)) {
3334 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3335 device, address.string());
3336 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3337 NULL/*patch handle*/, address.string());
3338 }
Eric Laurente552edb2014-03-10 17:42:56 -07003339 ALOGV("checkOutputsForDevice(): adding output %d", output);
3340 }
3341 }
3342
3343 if (profiles.isEmpty()) {
3344 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3345 return BAD_VALUE;
3346 }
Eric Laurentd4692962014-05-05 18:13:44 -07003347 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003348 // check if one opened output is not needed any more after disconnecting one device
3349 for (size_t i = 0; i < mOutputs.size(); i++) {
3350 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003351 if (!desc->isDuplicated()) {
3352 if (!(desc->mProfile->mSupportedDevices.types()
3353 & mAvailableOutputDevices.types())) {
3354 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3355 mOutputs.keyAt(i));
3356 outputs.add(mOutputs.keyAt(i));
3357 } else if (deviceDistinguishesOnAddress(device) &&
3358 // exact match on device
3359 (desc->mProfile->mSupportedDevices.types() == device)) {
3360 findIoHandlesByAddress(desc, address, outputs);
3361 }
Eric Laurente552edb2014-03-10 17:42:56 -07003362 }
3363 }
Eric Laurentd4692962014-05-05 18:13:44 -07003364 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003365 for (size_t i = 0; i < mHwModules.size(); i++)
3366 {
3367 if (mHwModules[i]->mHandle == 0) {
3368 continue;
3369 }
3370 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3371 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003372 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003373 if (profile->mSupportedDevices.types() & device) {
3374 ALOGV("checkOutputsForDevice(): "
3375 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003376 if (profile->mSamplingRates[0] == 0) {
3377 profile->mSamplingRates.clear();
3378 profile->mSamplingRates.add(0);
3379 }
3380 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3381 profile->mFormats.clear();
3382 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3383 }
3384 if (profile->mChannelMasks[0] == 0) {
3385 profile->mChannelMasks.clear();
3386 profile->mChannelMasks.add(0);
3387 }
3388 }
3389 }
3390 }
3391 }
3392 return NO_ERROR;
3393}
3394
Eric Laurentd4692962014-05-05 18:13:44 -07003395status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3396 audio_policy_dev_state_t state,
3397 SortedVector<audio_io_handle_t>& inputs,
3398 const String8 address)
3399{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003400 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003401 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3402 // first list already open inputs that can be routed to this device
3403 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3404 desc = mInputs.valueAt(input_index);
3405 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3406 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3407 inputs.add(mInputs.keyAt(input_index));
3408 }
3409 }
3410
3411 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003412 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003413 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3414 {
3415 if (mHwModules[module_idx]->mHandle == 0) {
3416 continue;
3417 }
3418 for (size_t profile_index = 0;
3419 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3420 profile_index++)
3421 {
3422 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3423 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003424 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003425 profile_index, module_idx);
3426 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3427 }
3428 }
3429 }
3430
3431 if (profiles.isEmpty() && inputs.isEmpty()) {
3432 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3433 return BAD_VALUE;
3434 }
3435
3436 // open inputs for matching profiles if needed. Direct inputs are also opened to
3437 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3438 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3439
Eric Laurent1c333e22014-05-20 10:48:17 -07003440 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003441 // nothing to do if one input is already opened for this profile
3442 size_t input_index;
3443 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3444 desc = mInputs.valueAt(input_index);
3445 if (desc->mProfile == profile) {
3446 break;
3447 }
3448 }
3449 if (input_index != mInputs.size()) {
3450 continue;
3451 }
3452
3453 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3454 desc = new AudioInputDescriptor(profile);
3455 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003456 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3457 config.sample_rate = desc->mSamplingRate;
3458 config.channel_mask = desc->mChannelMask;
3459 config.format = desc->mFormat;
3460 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3461 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3462 &input,
3463 &config,
3464 &desc->mDevice,
3465 address,
3466 AUDIO_SOURCE_MIC,
3467 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003468
Eric Laurentcf2c0212014-07-25 16:20:43 -07003469 if (status == NO_ERROR) {
3470 desc->mSamplingRate = config.sample_rate;
3471 desc->mChannelMask = config.channel_mask;
3472 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003473
Eric Laurentd4692962014-05-05 18:13:44 -07003474 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003475 char *param = audio_device_address_to_parameter(device, address);
3476 mpClientInterface->setParameters(input, String8(param));
3477 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003478 }
3479
3480 // Here is where we step through and resolve any "dynamic" fields
3481 String8 reply;
3482 char *value;
3483 if (profile->mSamplingRates[0] == 0) {
3484 reply = mpClientInterface->getParameters(input,
3485 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3486 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3487 reply.string());
3488 value = strpbrk((char *)reply.string(), "=");
3489 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003490 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003491 }
3492 }
3493 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3494 reply = mpClientInterface->getParameters(input,
3495 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3496 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3497 value = strpbrk((char *)reply.string(), "=");
3498 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003499 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003500 }
3501 }
3502 if (profile->mChannelMasks[0] == 0) {
3503 reply = mpClientInterface->getParameters(input,
3504 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3505 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3506 reply.string());
3507 value = strpbrk((char *)reply.string(), "=");
3508 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003509 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003510 }
3511 }
3512 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3513 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3514 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3515 ALOGW("checkInputsForDevice() direct input missing param");
3516 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003517 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003518 }
3519
3520 if (input != 0) {
3521 addInput(input, desc);
3522 }
3523 } // endif input != 0
3524
Eric Laurentcf2c0212014-07-25 16:20:43 -07003525 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003526 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003527 profiles.removeAt(profile_index);
3528 profile_index--;
3529 } else {
3530 inputs.add(input);
3531 ALOGV("checkInputsForDevice(): adding input %d", input);
3532 }
3533 } // end scan profiles
3534
3535 if (profiles.isEmpty()) {
3536 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3537 return BAD_VALUE;
3538 }
3539 } else {
3540 // Disconnect
3541 // check if one opened input is not needed any more after disconnecting one device
3542 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3543 desc = mInputs.valueAt(input_index);
3544 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3545 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3546 mInputs.keyAt(input_index));
3547 inputs.add(mInputs.keyAt(input_index));
3548 }
3549 }
3550 // Clear any profiles associated with the disconnected device.
3551 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3552 if (mHwModules[module_index]->mHandle == 0) {
3553 continue;
3554 }
3555 for (size_t profile_index = 0;
3556 profile_index < mHwModules[module_index]->mInputProfiles.size();
3557 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003558 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003559 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003560 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003561 profile_index, module_index);
3562 if (profile->mSamplingRates[0] == 0) {
3563 profile->mSamplingRates.clear();
3564 profile->mSamplingRates.add(0);
3565 }
3566 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3567 profile->mFormats.clear();
3568 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3569 }
3570 if (profile->mChannelMasks[0] == 0) {
3571 profile->mChannelMasks.clear();
3572 profile->mChannelMasks.add(0);
3573 }
3574 }
3575 }
3576 }
3577 } // end disconnect
3578
3579 return NO_ERROR;
3580}
3581
3582
Eric Laurente0720872014-03-11 09:30:41 -07003583void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003584{
3585 ALOGV("closeOutput(%d)", output);
3586
Eric Laurent1f2f2232014-06-02 12:01:23 -07003587 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003588 if (outputDesc == NULL) {
3589 ALOGW("closeOutput() unknown output %d", output);
3590 return;
3591 }
3592
3593 // look for duplicated outputs connected to the output being removed.
3594 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003595 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003596 if (dupOutputDesc->isDuplicated() &&
3597 (dupOutputDesc->mOutput1 == outputDesc ||
3598 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003599 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003600 if (dupOutputDesc->mOutput1 == outputDesc) {
3601 outputDesc2 = dupOutputDesc->mOutput2;
3602 } else {
3603 outputDesc2 = dupOutputDesc->mOutput1;
3604 }
3605 // As all active tracks on duplicated output will be deleted,
3606 // and as they were also referenced on the other output, the reference
3607 // count for their stream type must be adjusted accordingly on
3608 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003609 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003610 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003611 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003612 }
3613 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3614 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3615
3616 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003617 mOutputs.removeItem(duplicatedOutput);
3618 }
3619 }
3620
Eric Laurent05b90f82014-08-27 15:32:29 -07003621 nextAudioPortGeneration();
3622
3623 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3624 if (index >= 0) {
3625 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3626 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3627 mAudioPatches.removeItemsAt(index);
3628 mpClientInterface->onAudioPatchListUpdate();
3629 }
3630
Eric Laurente552edb2014-03-10 17:42:56 -07003631 AudioParameter param;
3632 param.add(String8("closing"), String8("true"));
3633 mpClientInterface->setParameters(output, param.toString());
3634
3635 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003636 mOutputs.removeItem(output);
3637 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003638}
3639
3640void AudioPolicyManager::closeInput(audio_io_handle_t input)
3641{
3642 ALOGV("closeInput(%d)", input);
3643
3644 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3645 if (inputDesc == NULL) {
3646 ALOGW("closeInput() unknown input %d", input);
3647 return;
3648 }
3649
Eric Laurent6a94d692014-05-20 11:18:06 -07003650 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003651
3652 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3653 if (index >= 0) {
3654 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3655 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3656 mAudioPatches.removeItemsAt(index);
3657 mpClientInterface->onAudioPatchListUpdate();
3658 }
3659
3660 mpClientInterface->closeInput(input);
3661 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003662}
3663
Eric Laurente0720872014-03-11 09:30:41 -07003664SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003665 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003666{
3667 SortedVector<audio_io_handle_t> outputs;
3668
3669 ALOGVV("getOutputsForDevice() device %04x", device);
3670 for (size_t i = 0; i < openOutputs.size(); i++) {
3671 ALOGVV("output %d isDuplicated=%d device=%04x",
3672 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3673 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3674 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3675 outputs.add(openOutputs.keyAt(i));
3676 }
3677 }
3678 return outputs;
3679}
3680
Eric Laurente0720872014-03-11 09:30:41 -07003681bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003682 SortedVector<audio_io_handle_t>& outputs2)
3683{
3684 if (outputs1.size() != outputs2.size()) {
3685 return false;
3686 }
3687 for (size_t i = 0; i < outputs1.size(); i++) {
3688 if (outputs1[i] != outputs2[i]) {
3689 return false;
3690 }
3691 }
3692 return true;
3693}
3694
Eric Laurente0720872014-03-11 09:30:41 -07003695void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003696{
3697 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3698 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3699 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3700 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3701
3702 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3703 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3704 strategy, srcOutputs[0], dstOutputs[0]);
3705 // mute strategy while moving tracks from one output to another
3706 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003707 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003708 if (desc->isStrategyActive(strategy)) {
3709 setStrategyMute(strategy, true, srcOutputs[i]);
3710 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3711 }
3712 }
3713
3714 // Move effects associated to this strategy from previous output to new output
3715 if (strategy == STRATEGY_MEDIA) {
3716 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3717 SortedVector<audio_io_handle_t> moved;
3718 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003719 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3720 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3721 effectDesc->mIo != fxOutput) {
3722 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003723 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3724 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003725 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003726 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003727 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003728 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003729 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003730 }
3731 }
3732 }
3733 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003734 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3735 if (getStrategy((audio_stream_type_t)i) == strategy) {
3736 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003737 }
3738 }
3739 }
3740}
3741
Eric Laurente0720872014-03-11 09:30:41 -07003742void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003743{
Jon Eklund966095e2014-09-09 15:39:49 -05003744 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3745 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003746 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05003747 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3748 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003749 checkOutputForStrategy(STRATEGY_SONIFICATION);
3750 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3751 checkOutputForStrategy(STRATEGY_MEDIA);
3752 checkOutputForStrategy(STRATEGY_DTMF);
3753}
3754
Eric Laurente0720872014-03-11 09:30:41 -07003755audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003756{
Eric Laurente552edb2014-03-10 17:42:56 -07003757 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003758 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003759 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3760 return mOutputs.keyAt(i);
3761 }
3762 }
3763
3764 return 0;
3765}
3766
Eric Laurente0720872014-03-11 09:30:41 -07003767void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003768{
Eric Laurente552edb2014-03-10 17:42:56 -07003769 audio_io_handle_t a2dpOutput = getA2dpOutput();
3770 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003771 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003772 return;
3773 }
3774
Eric Laurent3a4311c2014-03-17 12:00:47 -07003775 bool isScoConnected =
3776 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003777 // suspend A2DP output if:
3778 // (NOT already suspended) &&
3779 // ((SCO device is connected &&
3780 // (forced usage for communication || for record is SCO))) ||
3781 // (phone state is ringing || in call)
3782 //
3783 // restore A2DP output if:
3784 // (Already suspended) &&
3785 // ((SCO device is NOT connected ||
3786 // (forced usage NOT for communication && NOT for record is SCO))) &&
3787 // (phone state is NOT ringing && NOT in call)
3788 //
3789 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003790 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003791 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3792 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3793 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3794 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003795
3796 mpClientInterface->restoreOutput(a2dpOutput);
3797 mA2dpSuspended = false;
3798 }
3799 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003800 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003801 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3802 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3803 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3804 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003805
3806 mpClientInterface->suspendOutput(a2dpOutput);
3807 mA2dpSuspended = true;
3808 }
3809 }
3810}
3811
Eric Laurent1c333e22014-05-20 10:48:17 -07003812audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003813{
3814 audio_devices_t device = AUDIO_DEVICE_NONE;
3815
Eric Laurent1f2f2232014-06-02 12:01:23 -07003816 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003817
3818 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3819 if (index >= 0) {
3820 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3821 if (patchDesc->mUid != mUidCached) {
3822 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3823 outputDesc->device(), outputDesc->mPatchHandle);
3824 return outputDesc->device();
3825 }
3826 }
3827
Eric Laurente552edb2014-03-10 17:42:56 -07003828 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05003829 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003830 // use device for strategy enforced audible
3831 // 2: we are in call or the strategy phone is active on the output:
3832 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05003833 // 3: the strategy for enforced audible is active but not enforced on the output:
3834 // use the device for strategy enforced audible
3835 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003836 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003837 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003838 // use device for strategy "respectful" sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003839 // 6: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003840 // use device for strategy media
Jon Eklund966095e2014-09-09 15:39:49 -05003841 // 7: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003842 // use device for strategy DTMF
Jon Eklund966095e2014-09-09 15:39:49 -05003843 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
3844 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07003845 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3846 } else if (isInCall() ||
3847 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3848 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05003849 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3850 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003851 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3852 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3853 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3854 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3855 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3856 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3857 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3858 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3859 }
3860
Eric Laurent1c333e22014-05-20 10:48:17 -07003861 ALOGV("getNewOutputDevice() selected device %x", device);
3862 return device;
3863}
3864
3865audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3866{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003867 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003868
3869 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3870 if (index >= 0) {
3871 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3872 if (patchDesc->mUid != mUidCached) {
3873 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3874 inputDesc->mDevice, inputDesc->mPatchHandle);
3875 return inputDesc->mDevice;
3876 }
3877 }
3878
Eric Laurent1c333e22014-05-20 10:48:17 -07003879 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3880
3881 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003882 return device;
3883}
3884
Eric Laurente0720872014-03-11 09:30:41 -07003885uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003886 return (uint32_t)getStrategy(stream);
3887}
3888
Eric Laurente0720872014-03-11 09:30:41 -07003889audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003890 // By checking the range of stream before calling getStrategy, we avoid
3891 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3892 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003893 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003894 return AUDIO_DEVICE_NONE;
3895 }
3896 audio_devices_t devices;
3897 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3898 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3899 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3900 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003901 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003902 if (outputDesc->isStrategyActive(strategy)) {
3903 devices = outputDesc->device();
3904 break;
3905 }
Eric Laurente552edb2014-03-10 17:42:56 -07003906 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05003907
3908 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
3909 and doesn't really need to.*/
3910 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
3911 devices |= AUDIO_DEVICE_OUT_SPEAKER;
3912 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
3913 }
3914
Eric Laurente552edb2014-03-10 17:42:56 -07003915 return devices;
3916}
3917
Eric Laurente0720872014-03-11 09:30:41 -07003918AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003919 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003920 // stream to strategy mapping
3921 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003922 case AUDIO_STREAM_VOICE_CALL:
3923 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003924 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003925 case AUDIO_STREAM_RING:
3926 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003927 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003928 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003929 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003930 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003931 return STRATEGY_DTMF;
3932 default:
3933 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003934 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003935 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3936 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003937 case AUDIO_STREAM_TTS:
3938 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003939 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003940 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003941 return STRATEGY_ENFORCED_AUDIBLE;
3942 }
3943}
3944
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003945uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3946 // flags to strategy mapping
3947 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3948 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3949 }
3950
3951 // usage to strategy mapping
3952 switch (attr->usage) {
3953 case AUDIO_USAGE_MEDIA:
3954 case AUDIO_USAGE_GAME:
3955 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3956 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3957 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3958 return (uint32_t) STRATEGY_MEDIA;
3959
3960 case AUDIO_USAGE_VOICE_COMMUNICATION:
3961 return (uint32_t) STRATEGY_PHONE;
3962
3963 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3964 return (uint32_t) STRATEGY_DTMF;
3965
3966 case AUDIO_USAGE_ALARM:
3967 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3968 return (uint32_t) STRATEGY_SONIFICATION;
3969
3970 case AUDIO_USAGE_NOTIFICATION:
3971 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3972 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3973 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3974 case AUDIO_USAGE_NOTIFICATION_EVENT:
3975 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3976
3977 case AUDIO_USAGE_UNKNOWN:
3978 default:
3979 return (uint32_t) STRATEGY_MEDIA;
3980 }
3981}
3982
Eric Laurente0720872014-03-11 09:30:41 -07003983void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003984 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003985 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003986 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3987 updateDevicesAndOutputs();
3988 break;
3989 default:
3990 break;
3991 }
3992}
3993
Eric Laurente0720872014-03-11 09:30:41 -07003994audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003995 bool fromCache)
3996{
3997 uint32_t device = AUDIO_DEVICE_NONE;
3998
3999 if (fromCache) {
4000 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4001 strategy, mDeviceForStrategy[strategy]);
4002 return mDeviceForStrategy[strategy];
4003 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004004 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004005 switch (strategy) {
4006
4007 case STRATEGY_SONIFICATION_RESPECTFUL:
4008 if (isInCall()) {
4009 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004010 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004011 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4012 // while media is playing on a remote device, use the the sonification behavior.
4013 // Note that we test this usecase before testing if media is playing because
4014 // the isStreamActive() method only informs about the activity of a stream, not
4015 // if it's for local playback. Note also that we use the same delay between both tests
4016 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004017 //user "safe" speaker if available instead of normal speaker to avoid triggering
4018 //other acoustic safety mechanisms for notification
4019 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4020 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004021 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004022 // while media is playing (or has recently played), use the same device
4023 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4024 } else {
4025 // when media is not playing anymore, fall back on the sonification behavior
4026 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004027 //user "safe" speaker if available instead of normal speaker to avoid triggering
4028 //other acoustic safety mechanisms for notification
4029 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4030 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004031 }
4032
4033 break;
4034
4035 case STRATEGY_DTMF:
4036 if (!isInCall()) {
4037 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4038 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4039 break;
4040 }
4041 // when in call, DTMF and PHONE strategies follow the same rules
4042 // FALL THROUGH
4043
4044 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004045 // Force use of only devices on primary output if:
4046 // - in call AND
4047 // - cannot route from voice call RX OR
4048 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4049 if (mPhoneState == AUDIO_MODE_IN_CALL) {
4050 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4051 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4052 if (((mAvailableInputDevices.types() &
4053 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4054 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004055 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004056 AUDIO_DEVICE_API_VERSION_3_0))) {
4057 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4058 }
4059 }
Eric Laurente552edb2014-03-10 17:42:56 -07004060 // for phone strategy, we first consider the forced use and then the available devices by order
4061 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004062 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4063 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004064 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004065 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004066 if (device) break;
4067 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004068 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004069 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004070 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004071 if (device) break;
4072 // if SCO device is requested but no SCO device is available, fall back to default case
4073 // FALL THROUGH
4074
4075 default: // FORCE_NONE
4076 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004077 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004078 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004079 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004080 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004081 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004082 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004083 if (device) break;
4084 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004085 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004086 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004087 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004088 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004089 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4090 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004091 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004092 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004093 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004094 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004095 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004096 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004097 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004098 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004099 if (device) break;
4100 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004101 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004102 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004103 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004104 if (device == AUDIO_DEVICE_NONE) {
4105 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4106 }
4107 break;
4108
Eric Laurent3b73df72014-03-11 09:06:29 -07004109 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004110 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4111 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004112 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004113 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004114 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004115 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004116 if (device) break;
4117 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004118 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004119 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004120 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004121 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004122 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004123 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004124 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004125 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004126 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004127 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004128 if (device) break;
4129 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004130 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4131 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004132 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004133 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004134 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004135 if (device == AUDIO_DEVICE_NONE) {
4136 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4137 }
4138 break;
4139 }
4140 break;
4141
4142 case STRATEGY_SONIFICATION:
4143
4144 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4145 // handleIncallSonification().
4146 if (isInCall()) {
4147 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4148 break;
4149 }
4150 // FALL THROUGH
4151
4152 case STRATEGY_ENFORCED_AUDIBLE:
4153 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4154 // except:
4155 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4156 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4157
4158 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004159 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004160 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004161 if (device == AUDIO_DEVICE_NONE) {
4162 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4163 }
4164 }
4165 // The second device used for sonification is the same as the device used by media strategy
4166 // FALL THROUGH
4167
4168 case STRATEGY_MEDIA: {
4169 uint32_t device2 = AUDIO_DEVICE_NONE;
4170 if (strategy != STRATEGY_SONIFICATION) {
4171 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004172 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004173 }
4174 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004175 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004176 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004177 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004178 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004179 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004180 }
4181 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004182 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004183 }
4184 }
Hochi Huang327cb702014-09-21 09:47:31 +08004185 if ((device2 == AUDIO_DEVICE_NONE) &&
4186 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4187 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4188 }
Eric Laurente552edb2014-03-10 17:42:56 -07004189 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004190 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004191 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004192 if ((device2 == AUDIO_DEVICE_NONE)) {
4193 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4194 }
Eric Laurente552edb2014-03-10 17:42:56 -07004195 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004196 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004197 }
4198 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004199 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004200 }
4201 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004202 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004203 }
4204 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004205 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004206 }
4207 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4208 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004209 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004210 }
4211 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004212 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004213 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004214 }
4215 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004216 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004217 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004218 int device3 = AUDIO_DEVICE_NONE;
4219 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004220 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004221 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4222 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004223 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004224 }
Eric Laurente552edb2014-03-10 17:42:56 -07004225
Jungshik Jang839e4f32014-06-26 17:23:40 +09004226 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004227 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4228 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4229 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004230
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004231 // If hdmi system audio mode is on, remove speaker out of output list.
4232 if ((strategy == STRATEGY_MEDIA) &&
4233 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4234 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4235 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4236 }
4237
Eric Laurente552edb2014-03-10 17:42:56 -07004238 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004239 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004240 if (device == AUDIO_DEVICE_NONE) {
4241 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4242 }
4243 } break;
4244
4245 default:
4246 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4247 break;
4248 }
4249
4250 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4251 return device;
4252}
4253
Eric Laurente0720872014-03-11 09:30:41 -07004254void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004255{
4256 for (int i = 0; i < NUM_STRATEGIES; i++) {
4257 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4258 }
4259 mPreviousOutputs = mOutputs;
4260}
4261
Eric Laurent1f2f2232014-06-02 12:01:23 -07004262uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004263 audio_devices_t prevDevice,
4264 uint32_t delayMs)
4265{
4266 // mute/unmute strategies using an incompatible device combination
4267 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4268 // if unmuting, unmute only after the specified delay
4269 if (outputDesc->isDuplicated()) {
4270 return 0;
4271 }
4272
4273 uint32_t muteWaitMs = 0;
4274 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004275 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004276
4277 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4278 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004279 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004280 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4281 bool doMute = false;
4282
4283 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4284 doMute = true;
4285 outputDesc->mStrategyMutedByDevice[i] = true;
4286 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4287 doMute = true;
4288 outputDesc->mStrategyMutedByDevice[i] = false;
4289 }
Eric Laurent99401132014-05-07 19:48:15 -07004290 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004291 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004292 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004293 // skip output if it does not share any device with current output
4294 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4295 == AUDIO_DEVICE_NONE) {
4296 continue;
4297 }
4298 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4299 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4300 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4301 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4302 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004303 if (mute) {
4304 // FIXME: should not need to double latency if volume could be applied
4305 // immediately by the audioflinger mixer. We must account for the delay
4306 // between now and the next time the audioflinger thread for this output
4307 // will process a buffer (which corresponds to one buffer size,
4308 // usually 1/2 or 1/4 of the latency).
4309 if (muteWaitMs < desc->latency() * 2) {
4310 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004311 }
4312 }
4313 }
4314 }
4315 }
4316 }
4317
Eric Laurent99401132014-05-07 19:48:15 -07004318 // temporary mute output if device selection changes to avoid volume bursts due to
4319 // different per device volumes
4320 if (outputDesc->isActive() && (device != prevDevice)) {
4321 if (muteWaitMs < outputDesc->latency() * 2) {
4322 muteWaitMs = outputDesc->latency() * 2;
4323 }
4324 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4325 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004326 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004327 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004328 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004329 muteWaitMs *2, device);
4330 }
4331 }
4332 }
4333
Eric Laurente552edb2014-03-10 17:42:56 -07004334 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4335 if (muteWaitMs > delayMs) {
4336 muteWaitMs -= delayMs;
4337 usleep(muteWaitMs * 1000);
4338 return muteWaitMs;
4339 }
4340 return 0;
4341}
4342
Eric Laurente0720872014-03-11 09:30:41 -07004343uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004344 audio_devices_t device,
4345 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004346 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004347 audio_patch_handle_t *patchHandle,
4348 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004349{
4350 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004351 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004352 AudioParameter param;
4353 uint32_t muteWaitMs;
4354
4355 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004356 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4357 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004358 return muteWaitMs;
4359 }
4360 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4361 // output profile
4362 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004363 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004364 return 0;
4365 }
4366
4367 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004368 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004369
4370 audio_devices_t prevDevice = outputDesc->mDevice;
4371
4372 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4373
4374 if (device != AUDIO_DEVICE_NONE) {
4375 outputDesc->mDevice = device;
4376 }
4377 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4378
4379 // Do not change the routing if:
4380 // - the requested device is AUDIO_DEVICE_NONE
4381 // - the requested device is the same as current device and force is not specified.
4382 // Doing this check here allows the caller to call setOutputDevice() without conditions
4383 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
4384 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
4385 return muteWaitMs;
4386 }
4387
4388 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004389
Eric Laurente552edb2014-03-10 17:42:56 -07004390 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004391 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004392 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004393 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004394 DeviceVector deviceList = (address == NULL) ?
4395 mAvailableOutputDevices.getDevicesFromType(device)
4396 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004397 if (!deviceList.isEmpty()) {
4398 struct audio_patch patch;
4399 outputDesc->toAudioPortConfig(&patch.sources[0]);
4400 patch.num_sources = 1;
4401 patch.num_sinks = 0;
4402 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4403 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004404 patch.num_sinks++;
4405 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004406 ssize_t index;
4407 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4408 index = mAudioPatches.indexOfKey(*patchHandle);
4409 } else {
4410 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4411 }
4412 sp< AudioPatch> patchDesc;
4413 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4414 if (index >= 0) {
4415 patchDesc = mAudioPatches.valueAt(index);
4416 afPatchHandle = patchDesc->mAfPatchHandle;
4417 }
4418
Eric Laurent1c333e22014-05-20 10:48:17 -07004419 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004420 &afPatchHandle,
4421 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004422 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4423 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004424 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004425 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004426 if (index < 0) {
4427 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4428 &patch, mUidCached);
4429 addAudioPatch(patchDesc->mHandle, patchDesc);
4430 } else {
4431 patchDesc->mPatch = patch;
4432 }
4433 patchDesc->mAfPatchHandle = afPatchHandle;
4434 patchDesc->mUid = mUidCached;
4435 if (patchHandle) {
4436 *patchHandle = patchDesc->mHandle;
4437 }
4438 outputDesc->mPatchHandle = patchDesc->mHandle;
4439 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004440 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004441 }
4442 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004443
4444 // inform all input as well
4445 for (size_t i = 0; i < mInputs.size(); i++) {
4446 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4447 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4448 AudioParameter inputCmd = AudioParameter();
4449 ALOGV("%s: inform input %d of device:%d", __func__,
4450 inputDescriptor->mIoHandle, device);
4451 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4452 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4453 inputCmd.toString(),
4454 delayMs);
4455 }
4456 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004457 }
Eric Laurente552edb2014-03-10 17:42:56 -07004458
4459 // update stream volumes according to new device
4460 applyStreamVolumes(output, device, delayMs);
4461
4462 return muteWaitMs;
4463}
4464
Eric Laurent1c333e22014-05-20 10:48:17 -07004465status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004466 int delayMs,
4467 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004468{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004469 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004470 ssize_t index;
4471 if (patchHandle) {
4472 index = mAudioPatches.indexOfKey(*patchHandle);
4473 } else {
4474 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4475 }
4476 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004477 return INVALID_OPERATION;
4478 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004479 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4480 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004481 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4482 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004483 removeAudioPatch(patchDesc->mHandle);
4484 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004485 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004486 return status;
4487}
4488
4489status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4490 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004491 bool force,
4492 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004493{
4494 status_t status = NO_ERROR;
4495
Eric Laurent1f2f2232014-06-02 12:01:23 -07004496 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004497 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4498 inputDesc->mDevice = device;
4499
4500 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4501 if (!deviceList.isEmpty()) {
4502 struct audio_patch patch;
4503 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004504 // AUDIO_SOURCE_HOTWORD is for internal use only:
4505 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004506 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4507 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004508 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4509 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004510 patch.num_sinks = 1;
4511 //only one input device for now
4512 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004513 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004514 ssize_t index;
4515 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4516 index = mAudioPatches.indexOfKey(*patchHandle);
4517 } else {
4518 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4519 }
4520 sp< AudioPatch> patchDesc;
4521 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4522 if (index >= 0) {
4523 patchDesc = mAudioPatches.valueAt(index);
4524 afPatchHandle = patchDesc->mAfPatchHandle;
4525 }
4526
Eric Laurent1c333e22014-05-20 10:48:17 -07004527 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004528 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004529 0);
4530 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004531 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004532 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004533 if (index < 0) {
4534 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4535 &patch, mUidCached);
4536 addAudioPatch(patchDesc->mHandle, patchDesc);
4537 } else {
4538 patchDesc->mPatch = patch;
4539 }
4540 patchDesc->mAfPatchHandle = afPatchHandle;
4541 patchDesc->mUid = mUidCached;
4542 if (patchHandle) {
4543 *patchHandle = patchDesc->mHandle;
4544 }
4545 inputDesc->mPatchHandle = patchDesc->mHandle;
4546 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004547 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004548 }
4549 }
4550 }
4551 return status;
4552}
4553
Eric Laurent6a94d692014-05-20 11:18:06 -07004554status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4555 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004556{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004557 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004558 ssize_t index;
4559 if (patchHandle) {
4560 index = mAudioPatches.indexOfKey(*patchHandle);
4561 } else {
4562 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4563 }
4564 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004565 return INVALID_OPERATION;
4566 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004567 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4568 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004569 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4570 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004571 removeAudioPatch(patchDesc->mHandle);
4572 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004573 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004574 return status;
4575}
4576
4577sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004578 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004579 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004580 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004581 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004582{
4583 // Choose an input profile based on the requested capture parameters: select the first available
4584 // profile supporting all requested parameters.
4585
4586 for (size_t i = 0; i < mHwModules.size(); i++)
4587 {
4588 if (mHwModules[i]->mHandle == 0) {
4589 continue;
4590 }
4591 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4592 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004593 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004594 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004595 if (profile->isCompatibleProfile(device, samplingRate,
4596 &samplingRate /*updatedSamplingRate*/,
4597 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004598 return profile;
4599 }
4600 }
4601 }
4602 return NULL;
4603}
4604
Eric Laurente0720872014-03-11 09:30:41 -07004605audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004606{
4607 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004608 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4609 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004610 switch (inputSource) {
4611 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004612 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004613 device = AUDIO_DEVICE_IN_VOICE_CALL;
4614 break;
4615 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004616 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004617
4618 case AUDIO_SOURCE_DEFAULT:
4619 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004620 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4621 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004622 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4623 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4624 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4625 device = AUDIO_DEVICE_IN_USB_DEVICE;
4626 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4627 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004628 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004629 break;
4630
4631 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4632 // Allow only use of devices on primary input if in call and HAL does not support routing
4633 // to voice call path.
4634 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4635 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4636 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4637 }
4638
4639 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4640 case AUDIO_POLICY_FORCE_BT_SCO:
4641 // if SCO device is requested but no SCO device is available, fall back to default case
4642 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4643 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4644 break;
4645 }
4646 // FALL THROUGH
4647
4648 default: // FORCE_NONE
4649 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4650 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4651 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4652 device = AUDIO_DEVICE_IN_USB_DEVICE;
4653 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4654 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4655 }
4656 break;
4657
4658 case AUDIO_POLICY_FORCE_SPEAKER:
4659 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4660 device = AUDIO_DEVICE_IN_BACK_MIC;
4661 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4662 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4663 }
4664 break;
4665 }
4666 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004667
Eric Laurente552edb2014-03-10 17:42:56 -07004668 case AUDIO_SOURCE_VOICE_RECOGNITION:
4669 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004670 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004671 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004672 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004673 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004674 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004675 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4676 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004677 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004678 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4679 }
4680 break;
4681 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004682 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004683 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004684 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004685 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4686 }
4687 break;
4688 case AUDIO_SOURCE_VOICE_DOWNLINK:
4689 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004690 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004691 device = AUDIO_DEVICE_IN_VOICE_CALL;
4692 }
4693 break;
4694 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004695 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004696 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4697 }
4698 break;
Hochi Huang327cb702014-09-21 09:47:31 +08004699 case AUDIO_SOURCE_FM_TUNER:
4700 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
4701 device = AUDIO_DEVICE_IN_FM_TUNER;
4702 }
4703 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004704 default:
4705 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4706 break;
4707 }
4708 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4709 return device;
4710}
4711
Eric Laurente0720872014-03-11 09:30:41 -07004712bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004713{
4714 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4715 device &= ~AUDIO_DEVICE_BIT_IN;
4716 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4717 return true;
4718 }
4719 return false;
4720}
4721
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004722bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4723 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4724}
4725
Eric Laurente0720872014-03-11 09:30:41 -07004726audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004727{
4728 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004729 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004730 if ((input_descriptor->mRefCount > 0)
4731 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4732 return mInputs.keyAt(i);
4733 }
4734 }
4735 return 0;
4736}
4737
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004738uint32_t AudioPolicyManager::activeInputsCount() const
4739{
4740 uint32_t count = 0;
4741 for (size_t i = 0; i < mInputs.size(); i++) {
4742 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4743 if (desc->mRefCount > 0) {
4744 return count++;
4745 }
4746 }
4747 return count;
4748}
4749
Eric Laurente552edb2014-03-10 17:42:56 -07004750
Eric Laurente0720872014-03-11 09:30:41 -07004751audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004752{
4753 if (device == AUDIO_DEVICE_NONE) {
4754 // this happens when forcing a route update and no track is active on an output.
4755 // In this case the returned category is not important.
4756 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004757 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004758 // Multiple device selection is either:
4759 // - speaker + one other device: give priority to speaker in this case.
4760 // - one A2DP device + another device: happens with duplicated output. In this case
4761 // retain the device on the A2DP output as the other must not correspond to an active
4762 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004763 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004764 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4765 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004766 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4767 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4768 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4769 device = AUDIO_DEVICE_OUT_AUX_LINE;
4770 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4771 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004772 } else {
4773 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4774 }
4775 }
4776
Jon Eklund11c9fb12014-06-23 14:47:03 -05004777 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4778 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4779 device = AUDIO_DEVICE_OUT_SPEAKER;
4780
Eric Laurent3b73df72014-03-11 09:06:29 -07004781 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004782 "getDeviceForVolume() invalid device combination: %08x",
4783 device);
4784
4785 return device;
4786}
4787
Eric Laurente0720872014-03-11 09:30:41 -07004788AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004789{
4790 switch(getDeviceForVolume(device)) {
4791 case AUDIO_DEVICE_OUT_EARPIECE:
4792 return DEVICE_CATEGORY_EARPIECE;
4793 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4794 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4795 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4796 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4797 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4798 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4799 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004800 case AUDIO_DEVICE_OUT_LINE:
4801 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4802 /*USB? Remote submix?*/
4803 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004804 case AUDIO_DEVICE_OUT_SPEAKER:
4805 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4806 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004807 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4808 case AUDIO_DEVICE_OUT_USB_DEVICE:
4809 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4810 default:
4811 return DEVICE_CATEGORY_SPEAKER;
4812 }
4813}
4814
Eric Laurente0720872014-03-11 09:30:41 -07004815float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004816 int indexInUi)
4817{
4818 device_category deviceCategory = getDeviceCategory(device);
4819 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4820
4821 // the volume index in the UI is relative to the min and max volume indices for this stream type
4822 int nbSteps = 1 + curve[VOLMAX].mIndex -
4823 curve[VOLMIN].mIndex;
4824 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4825 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4826
4827 // find what part of the curve this index volume belongs to, or if it's out of bounds
4828 int segment = 0;
4829 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4830 return 0.0f;
4831 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4832 segment = 0;
4833 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4834 segment = 1;
4835 } else if (volIdx <= curve[VOLMAX].mIndex) {
4836 segment = 2;
4837 } else { // out of bounds
4838 return 1.0f;
4839 }
4840
4841 // linear interpolation in the attenuation table in dB
4842 float decibels = curve[segment].mDBAttenuation +
4843 ((float)(volIdx - curve[segment].mIndex)) *
4844 ( (curve[segment+1].mDBAttenuation -
4845 curve[segment].mDBAttenuation) /
4846 ((float)(curve[segment+1].mIndex -
4847 curve[segment].mIndex)) );
4848
4849 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4850
4851 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4852 curve[segment].mIndex, volIdx,
4853 curve[segment+1].mIndex,
4854 curve[segment].mDBAttenuation,
4855 decibels,
4856 curve[segment+1].mDBAttenuation,
4857 amplification);
4858
4859 return amplification;
4860}
4861
Eric Laurente0720872014-03-11 09:30:41 -07004862const AudioPolicyManager::VolumeCurvePoint
4863 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004864 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4865};
4866
Eric Laurente0720872014-03-11 09:30:41 -07004867const AudioPolicyManager::VolumeCurvePoint
4868 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004869 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4870};
4871
Eric Laurente0720872014-03-11 09:30:41 -07004872const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004873 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4874 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4875};
4876
4877const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004878 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004879 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4880};
4881
Eric Laurente0720872014-03-11 09:30:41 -07004882const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004883 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004884 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004885};
4886
4887const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004888 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004889 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4890};
4891
Eric Laurente0720872014-03-11 09:30:41 -07004892const AudioPolicyManager::VolumeCurvePoint
4893 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004894 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4895};
4896
4897// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4898// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4899// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4900// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4901
Eric Laurente0720872014-03-11 09:30:41 -07004902const AudioPolicyManager::VolumeCurvePoint
4903 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004904 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4905};
4906
Eric Laurente0720872014-03-11 09:30:41 -07004907const AudioPolicyManager::VolumeCurvePoint
4908 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004909 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4910};
4911
Eric Laurente0720872014-03-11 09:30:41 -07004912const AudioPolicyManager::VolumeCurvePoint
4913 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004914 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4915};
4916
Eric Laurente0720872014-03-11 09:30:41 -07004917const AudioPolicyManager::VolumeCurvePoint
4918 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004919 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4920};
4921
Eric Laurente0720872014-03-11 09:30:41 -07004922const AudioPolicyManager::VolumeCurvePoint
4923 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004924 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4925};
4926
Eric Laurente0720872014-03-11 09:30:41 -07004927const AudioPolicyManager::VolumeCurvePoint
4928 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4929 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004930 { // AUDIO_STREAM_VOICE_CALL
4931 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4932 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004933 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4934 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004935 },
4936 { // AUDIO_STREAM_SYSTEM
4937 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4938 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004939 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4940 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004941 },
4942 { // AUDIO_STREAM_RING
4943 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4944 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004945 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4946 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004947 },
4948 { // AUDIO_STREAM_MUSIC
4949 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4950 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004951 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4952 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004953 },
4954 { // AUDIO_STREAM_ALARM
4955 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4956 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004957 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4958 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004959 },
4960 { // AUDIO_STREAM_NOTIFICATION
4961 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4962 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004963 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4964 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004965 },
4966 { // AUDIO_STREAM_BLUETOOTH_SCO
4967 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4968 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004969 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4970 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004971 },
4972 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4973 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4974 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004975 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4976 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004977 },
4978 { // AUDIO_STREAM_DTMF
4979 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4980 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004981 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4982 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004983 },
4984 { // AUDIO_STREAM_TTS
4985 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4986 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004987 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4988 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004989 },
4990};
4991
Eric Laurente0720872014-03-11 09:30:41 -07004992void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004993{
4994 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4995 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4996 mStreams[i].mVolumeCurve[j] =
4997 sVolumeProfiles[i][j];
4998 }
4999 }
5000
5001 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5002 if (mSpeakerDrcEnabled) {
5003 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5004 sDefaultSystemVolumeCurveDrc;
5005 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5006 sSpeakerSonificationVolumeCurveDrc;
5007 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5008 sSpeakerSonificationVolumeCurveDrc;
5009 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5010 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005011 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5012 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005013 }
5014}
5015
Eric Laurente0720872014-03-11 09:30:41 -07005016float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005017 int index,
5018 audio_io_handle_t output,
5019 audio_devices_t device)
5020{
5021 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005022 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005023 StreamDescriptor &streamDesc = mStreams[stream];
5024
5025 if (device == AUDIO_DEVICE_NONE) {
5026 device = outputDesc->device();
5027 }
5028
Eric Laurente552edb2014-03-10 17:42:56 -07005029 volume = volIndexToAmpl(device, streamDesc, index);
5030
5031 // if a headset is connected, apply the following rules to ring tones and notifications
5032 // to avoid sound level bursts in user's ears:
5033 // - always attenuate ring tones and notifications volume by 6dB
5034 // - if music is playing, always limit the volume to current music volume,
5035 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005036 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005037 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5038 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5039 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5040 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5041 ((stream_strategy == STRATEGY_SONIFICATION)
5042 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005043 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005044 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005045 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005046 streamDesc.mCanBeMuted) {
5047 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5048 // when the phone is ringing we must consider that music could have been paused just before
5049 // by the music application and behave as if music was active if the last music track was
5050 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005051 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005052 mLimitRingtoneVolume) {
5053 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005054 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5055 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005056 output,
5057 musicDevice);
5058 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5059 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5060 if (volume > minVol) {
5061 volume = minVol;
5062 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5063 }
5064 }
5065 }
5066
5067 return volume;
5068}
5069
Eric Laurente0720872014-03-11 09:30:41 -07005070status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005071 int index,
5072 audio_io_handle_t output,
5073 audio_devices_t device,
5074 int delayMs,
5075 bool force)
5076{
5077
5078 // do not change actual stream volume if the stream is muted
5079 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5080 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5081 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5082 return NO_ERROR;
5083 }
5084
5085 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005086 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5087 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5088 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5089 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005090 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005091 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005092 return INVALID_OPERATION;
5093 }
5094
5095 float volume = computeVolume(stream, index, output, device);
5096 // We actually change the volume if:
5097 // - the float value returned by computeVolume() changed
5098 // - the force flag is set
5099 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5100 force) {
5101 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5102 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5103 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5104 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005105 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5106 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005107 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005108 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005109 }
5110
Eric Laurent3b73df72014-03-11 09:06:29 -07005111 if (stream == AUDIO_STREAM_VOICE_CALL ||
5112 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005113 float voiceVolume;
5114 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005115 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005116 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5117 } else {
5118 voiceVolume = 1.0;
5119 }
5120
5121 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5122 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5123 mLastVoiceVolume = voiceVolume;
5124 }
5125 }
5126
5127 return NO_ERROR;
5128}
5129
Eric Laurente0720872014-03-11 09:30:41 -07005130void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005131 audio_devices_t device,
5132 int delayMs,
5133 bool force)
5134{
5135 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5136
Eric Laurent3b73df72014-03-11 09:06:29 -07005137 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5138 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005139 mStreams[stream].getVolumeIndex(device),
5140 output,
5141 device,
5142 delayMs,
5143 force);
5144 }
5145}
5146
Eric Laurente0720872014-03-11 09:30:41 -07005147void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005148 bool on,
5149 audio_io_handle_t output,
5150 int delayMs,
5151 audio_devices_t device)
5152{
5153 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005154 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5155 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5156 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005157 }
5158 }
5159}
5160
Eric Laurente0720872014-03-11 09:30:41 -07005161void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005162 bool on,
5163 audio_io_handle_t output,
5164 int delayMs,
5165 audio_devices_t device)
5166{
5167 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005168 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005169 if (device == AUDIO_DEVICE_NONE) {
5170 device = outputDesc->device();
5171 }
5172
5173 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5174 stream, on, output, outputDesc->mMuteCount[stream], device);
5175
5176 if (on) {
5177 if (outputDesc->mMuteCount[stream] == 0) {
5178 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005179 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5180 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005181 checkAndSetVolume(stream, 0, output, device, delayMs);
5182 }
5183 }
5184 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5185 outputDesc->mMuteCount[stream]++;
5186 } else {
5187 if (outputDesc->mMuteCount[stream] == 0) {
5188 ALOGV("setStreamMute() unmuting non muted stream!");
5189 return;
5190 }
5191 if (--outputDesc->mMuteCount[stream] == 0) {
5192 checkAndSetVolume(stream,
5193 streamDesc.getVolumeIndex(device),
5194 output,
5195 device,
5196 delayMs);
5197 }
5198 }
5199}
5200
Eric Laurente0720872014-03-11 09:30:41 -07005201void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005202 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005203{
5204 // if the stream pertains to sonification strategy and we are in call we must
5205 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5206 // in the device used for phone strategy and play the tone if the selected device does not
5207 // interfere with the device used for phone strategy
5208 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5209 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005210 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005211 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5212 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005213 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005214 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5215 stream, starting, outputDesc->mDevice, stateChange);
5216 if (outputDesc->mRefCount[stream]) {
5217 int muteCount = 1;
5218 if (stateChange) {
5219 muteCount = outputDesc->mRefCount[stream];
5220 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005221 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005222 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5223 for (int i = 0; i < muteCount; i++) {
5224 setStreamMute(stream, starting, mPrimaryOutput);
5225 }
5226 } else {
5227 ALOGV("handleIncallSonification() high visibility");
5228 if (outputDesc->device() &
5229 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5230 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5231 for (int i = 0; i < muteCount; i++) {
5232 setStreamMute(stream, starting, mPrimaryOutput);
5233 }
5234 }
5235 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005236 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5237 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005238 } else {
5239 mpClientInterface->stopTone();
5240 }
5241 }
5242 }
5243 }
5244}
5245
Eric Laurente0720872014-03-11 09:30:41 -07005246bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005247{
5248 return isStateInCall(mPhoneState);
5249}
5250
Eric Laurente0720872014-03-11 09:30:41 -07005251bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005252 return ((state == AUDIO_MODE_IN_CALL) ||
5253 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005254}
5255
Eric Laurente0720872014-03-11 09:30:41 -07005256uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005257{
5258 return MAX_EFFECTS_CPU_LOAD;
5259}
5260
Eric Laurente0720872014-03-11 09:30:41 -07005261uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005262{
5263 return MAX_EFFECTS_MEMORY;
5264}
5265
Eric Laurent6a94d692014-05-20 11:18:06 -07005266
Eric Laurente552edb2014-03-10 17:42:56 -07005267// --- AudioOutputDescriptor class implementation
5268
Eric Laurente0720872014-03-11 09:30:41 -07005269AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005270 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005271 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005272 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005273 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5274{
5275 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005276 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005277 mRefCount[i] = 0;
5278 mCurVolume[i] = -1.0;
5279 mMuteCount[i] = 0;
5280 mStopTime[i] = 0;
5281 }
5282 for (int i = 0; i < NUM_STRATEGIES; i++) {
5283 mStrategyMutedByDevice[i] = false;
5284 }
5285 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005286 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005287 mSamplingRate = profile->pickSamplingRate();
5288 mFormat = profile->pickFormat();
5289 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005290 if (profile->mGains.size() > 0) {
5291 profile->mGains[0]->getDefaultConfig(&mGain);
5292 }
Eric Laurente552edb2014-03-10 17:42:56 -07005293 }
5294}
5295
Eric Laurente0720872014-03-11 09:30:41 -07005296audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005297{
5298 if (isDuplicated()) {
5299 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5300 } else {
5301 return mDevice;
5302 }
5303}
5304
Eric Laurente0720872014-03-11 09:30:41 -07005305uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005306{
5307 if (isDuplicated()) {
5308 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5309 } else {
5310 return mLatency;
5311 }
5312}
5313
Eric Laurente0720872014-03-11 09:30:41 -07005314bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005315 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005316{
5317 if (isDuplicated()) {
5318 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5319 } else if (outputDesc->isDuplicated()){
5320 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5321 } else {
5322 return (mProfile->mModule == outputDesc->mProfile->mModule);
5323 }
5324}
5325
Eric Laurente0720872014-03-11 09:30:41 -07005326void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005327 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005328{
5329 // forward usage count change to attached outputs
5330 if (isDuplicated()) {
5331 mOutput1->changeRefCount(stream, delta);
5332 mOutput2->changeRefCount(stream, delta);
5333 }
5334 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005335 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5336 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005337 mRefCount[stream] = 0;
5338 return;
5339 }
5340 mRefCount[stream] += delta;
5341 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5342}
5343
Eric Laurente0720872014-03-11 09:30:41 -07005344audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005345{
5346 if (isDuplicated()) {
5347 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5348 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005349 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005350 }
5351}
5352
Eric Laurente0720872014-03-11 09:30:41 -07005353bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005354{
5355 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5356}
5357
Eric Laurente0720872014-03-11 09:30:41 -07005358bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005359 uint32_t inPastMs,
5360 nsecs_t sysTime) const
5361{
5362 if ((sysTime == 0) && (inPastMs != 0)) {
5363 sysTime = systemTime();
5364 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005365 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5366 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005367 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005368 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005369 return true;
5370 }
5371 }
5372 return false;
5373}
5374
Eric Laurente0720872014-03-11 09:30:41 -07005375bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005376 uint32_t inPastMs,
5377 nsecs_t sysTime) const
5378{
5379 if (mRefCount[stream] != 0) {
5380 return true;
5381 }
5382 if (inPastMs == 0) {
5383 return false;
5384 }
5385 if (sysTime == 0) {
5386 sysTime = systemTime();
5387 }
5388 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5389 return true;
5390 }
5391 return false;
5392}
5393
Eric Laurent1c333e22014-05-20 10:48:17 -07005394void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005395 struct audio_port_config *dstConfig,
5396 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005397{
Eric Laurent84c70242014-06-23 08:46:27 -07005398 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5399
Eric Laurent1f2f2232014-06-02 12:01:23 -07005400 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5401 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5402 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005403 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005404 }
5405 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5406
Eric Laurent6a94d692014-05-20 11:18:06 -07005407 dstConfig->id = mId;
5408 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5409 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005410 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5411 dstConfig->ext.mix.handle = mIoHandle;
5412 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005413}
5414
5415void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5416 struct audio_port *port) const
5417{
Eric Laurent84c70242014-06-23 08:46:27 -07005418 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005419 mProfile->toAudioPort(port);
5420 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005421 toAudioPortConfig(&port->active_config);
5422 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005423 port->ext.mix.handle = mIoHandle;
5424 port->ext.mix.latency_class =
5425 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5426}
Eric Laurente552edb2014-03-10 17:42:56 -07005427
Eric Laurente0720872014-03-11 09:30:41 -07005428status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005429{
5430 const size_t SIZE = 256;
5431 char buffer[SIZE];
5432 String8 result;
5433
Eric Laurent4d416952014-08-10 14:07:09 -07005434 snprintf(buffer, SIZE, " ID: %d\n", mId);
5435 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005436 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5437 result.append(buffer);
5438 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5439 result.append(buffer);
5440 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5441 result.append(buffer);
5442 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5443 result.append(buffer);
5444 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5445 result.append(buffer);
5446 snprintf(buffer, SIZE, " Devices %08x\n", device());
5447 result.append(buffer);
5448 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5449 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005450 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5451 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5452 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005453 result.append(buffer);
5454 }
5455 write(fd, result.string(), result.size());
5456
5457 return NO_ERROR;
5458}
5459
5460// --- AudioInputDescriptor class implementation
5461
Eric Laurent1c333e22014-05-20 10:48:17 -07005462AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005463 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005464 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005465 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005466{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005467 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005468 mSamplingRate = profile->pickSamplingRate();
5469 mFormat = profile->pickFormat();
5470 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005471 if (profile->mGains.size() > 0) {
5472 profile->mGains[0]->getDefaultConfig(&mGain);
5473 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005474 }
Eric Laurente552edb2014-03-10 17:42:56 -07005475}
5476
Eric Laurent1c333e22014-05-20 10:48:17 -07005477void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005478 struct audio_port_config *dstConfig,
5479 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005480{
Eric Laurent84c70242014-06-23 08:46:27 -07005481 ALOG_ASSERT(mProfile != 0,
5482 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005483 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5484 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5485 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005486 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005487 }
5488
5489 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5490
Eric Laurent6a94d692014-05-20 11:18:06 -07005491 dstConfig->id = mId;
5492 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5493 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005494 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5495 dstConfig->ext.mix.handle = mIoHandle;
5496 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005497}
5498
5499void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5500 struct audio_port *port) const
5501{
Eric Laurent84c70242014-06-23 08:46:27 -07005502 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5503
Eric Laurent1c333e22014-05-20 10:48:17 -07005504 mProfile->toAudioPort(port);
5505 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005506 toAudioPortConfig(&port->active_config);
5507 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005508 port->ext.mix.handle = mIoHandle;
5509 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5510}
5511
Eric Laurente0720872014-03-11 09:30:41 -07005512status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005513{
5514 const size_t SIZE = 256;
5515 char buffer[SIZE];
5516 String8 result;
5517
Eric Laurent4d416952014-08-10 14:07:09 -07005518 snprintf(buffer, SIZE, " ID: %d\n", mId);
5519 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005520 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5521 result.append(buffer);
5522 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5523 result.append(buffer);
5524 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5525 result.append(buffer);
5526 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5527 result.append(buffer);
5528 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5529 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005530 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5531 result.append(buffer);
5532
Eric Laurente552edb2014-03-10 17:42:56 -07005533 write(fd, result.string(), result.size());
5534
5535 return NO_ERROR;
5536}
5537
5538// --- StreamDescriptor class implementation
5539
Eric Laurente0720872014-03-11 09:30:41 -07005540AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005541 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5542{
5543 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5544}
5545
Eric Laurente0720872014-03-11 09:30:41 -07005546int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005547{
Eric Laurente0720872014-03-11 09:30:41 -07005548 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005549 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5550 if (mIndexCur.indexOfKey(device) < 0) {
5551 device = AUDIO_DEVICE_OUT_DEFAULT;
5552 }
5553 return mIndexCur.valueFor(device);
5554}
5555
Eric Laurente0720872014-03-11 09:30:41 -07005556void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005557{
5558 const size_t SIZE = 256;
5559 char buffer[SIZE];
5560 String8 result;
5561
5562 snprintf(buffer, SIZE, "%s %02d %02d ",
5563 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5564 result.append(buffer);
5565 for (size_t i = 0; i < mIndexCur.size(); i++) {
5566 snprintf(buffer, SIZE, "%04x : %02d, ",
5567 mIndexCur.keyAt(i),
5568 mIndexCur.valueAt(i));
5569 result.append(buffer);
5570 }
5571 result.append("\n");
5572
5573 write(fd, result.string(), result.size());
5574}
5575
5576// --- EffectDescriptor class implementation
5577
Eric Laurente0720872014-03-11 09:30:41 -07005578status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005579{
5580 const size_t SIZE = 256;
5581 char buffer[SIZE];
5582 String8 result;
5583
5584 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5585 result.append(buffer);
5586 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5587 result.append(buffer);
5588 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5589 result.append(buffer);
5590 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5591 result.append(buffer);
5592 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5593 result.append(buffer);
5594 write(fd, result.string(), result.size());
5595
5596 return NO_ERROR;
5597}
5598
Eric Laurent1c333e22014-05-20 10:48:17 -07005599// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005600
Eric Laurente0720872014-03-11 09:30:41 -07005601AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005602 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5603 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005604{
5605}
5606
Eric Laurente0720872014-03-11 09:30:41 -07005607AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005608{
5609 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005610 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005611 }
5612 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005613 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005614 }
5615 free((void *)mName);
5616}
5617
Eric Laurent1afeecb2014-05-14 08:52:28 -07005618status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5619{
5620 cnode *node = root->first_child;
5621
5622 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5623
5624 while (node) {
5625 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5626 profile->loadSamplingRates((char *)node->value);
5627 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5628 profile->loadFormats((char *)node->value);
5629 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5630 profile->loadInChannels((char *)node->value);
5631 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5632 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5633 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07005634 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5635 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005636 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5637 profile->loadGains(node);
5638 }
5639 node = node->next;
5640 }
5641 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5642 "loadInput() invalid supported devices");
5643 ALOGW_IF(profile->mChannelMasks.size() == 0,
5644 "loadInput() invalid supported channel masks");
5645 ALOGW_IF(profile->mSamplingRates.size() == 0,
5646 "loadInput() invalid supported sampling rates");
5647 ALOGW_IF(profile->mFormats.size() == 0,
5648 "loadInput() invalid supported formats");
5649 if (!profile->mSupportedDevices.isEmpty() &&
5650 (profile->mChannelMasks.size() != 0) &&
5651 (profile->mSamplingRates.size() != 0) &&
5652 (profile->mFormats.size() != 0)) {
5653
5654 ALOGV("loadInput() adding input Supported Devices %04x",
5655 profile->mSupportedDevices.types());
5656
5657 mInputProfiles.add(profile);
5658 return NO_ERROR;
5659 } else {
5660 return BAD_VALUE;
5661 }
5662}
5663
5664status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5665{
5666 cnode *node = root->first_child;
5667
5668 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5669
5670 while (node) {
5671 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5672 profile->loadSamplingRates((char *)node->value);
5673 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5674 profile->loadFormats((char *)node->value);
5675 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5676 profile->loadOutChannels((char *)node->value);
5677 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5678 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5679 mDeclaredDevices);
5680 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005681 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005682 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5683 profile->loadGains(node);
5684 }
5685 node = node->next;
5686 }
5687 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5688 "loadOutput() invalid supported devices");
5689 ALOGW_IF(profile->mChannelMasks.size() == 0,
5690 "loadOutput() invalid supported channel masks");
5691 ALOGW_IF(profile->mSamplingRates.size() == 0,
5692 "loadOutput() invalid supported sampling rates");
5693 ALOGW_IF(profile->mFormats.size() == 0,
5694 "loadOutput() invalid supported formats");
5695 if (!profile->mSupportedDevices.isEmpty() &&
5696 (profile->mChannelMasks.size() != 0) &&
5697 (profile->mSamplingRates.size() != 0) &&
5698 (profile->mFormats.size() != 0)) {
5699
5700 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5701 profile->mSupportedDevices.types(), profile->mFlags);
5702
5703 mOutputProfiles.add(profile);
5704 return NO_ERROR;
5705 } else {
5706 return BAD_VALUE;
5707 }
5708}
5709
5710status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5711{
5712 cnode *node = root->first_child;
5713
5714 audio_devices_t type = AUDIO_DEVICE_NONE;
5715 while (node) {
5716 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5717 type = parseDeviceNames((char *)node->value);
5718 break;
5719 }
5720 node = node->next;
5721 }
5722 if (type == AUDIO_DEVICE_NONE ||
5723 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5724 ALOGW("loadDevice() bad type %08x", type);
5725 return BAD_VALUE;
5726 }
5727 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5728 deviceDesc->mModule = this;
5729
5730 node = root->first_child;
5731 while (node) {
5732 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5733 deviceDesc->mAddress = String8((char *)node->value);
5734 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5735 if (audio_is_input_device(type)) {
5736 deviceDesc->loadInChannels((char *)node->value);
5737 } else {
5738 deviceDesc->loadOutChannels((char *)node->value);
5739 }
5740 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5741 deviceDesc->loadGains(node);
5742 }
5743 node = node->next;
5744 }
5745
5746 ALOGV("loadDevice() adding device name %s type %08x address %s",
5747 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5748
5749 mDeclaredDevices.add(deviceDesc);
5750
5751 return NO_ERROR;
5752}
5753
Eric Laurente0720872014-03-11 09:30:41 -07005754void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005755{
5756 const size_t SIZE = 256;
5757 char buffer[SIZE];
5758 String8 result;
5759
5760 snprintf(buffer, SIZE, " - name: %s\n", mName);
5761 result.append(buffer);
5762 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5763 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005764 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5765 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005766 write(fd, result.string(), result.size());
5767 if (mOutputProfiles.size()) {
5768 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5769 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005770 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005771 write(fd, buffer, strlen(buffer));
5772 mOutputProfiles[i]->dump(fd);
5773 }
5774 }
5775 if (mInputProfiles.size()) {
5776 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5777 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005778 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005779 write(fd, buffer, strlen(buffer));
5780 mInputProfiles[i]->dump(fd);
5781 }
5782 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005783 if (mDeclaredDevices.size()) {
5784 write(fd, " - devices:\n", strlen(" - devices:\n"));
5785 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5786 mDeclaredDevices[i]->dump(fd, 4, i);
5787 }
5788 }
Eric Laurente552edb2014-03-10 17:42:56 -07005789}
5790
Eric Laurent1c333e22014-05-20 10:48:17 -07005791// --- AudioPort class implementation
5792
Eric Laurenta121f902014-06-03 13:32:54 -07005793
5794AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5795 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07005796 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07005797{
5798 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5799 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5800}
5801
Eric Laurent1c333e22014-05-20 10:48:17 -07005802void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5803{
5804 port->role = mRole;
5805 port->type = mType;
5806 unsigned int i;
5807 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005808 if (mSamplingRates[i] != 0) {
5809 port->sample_rates[i] = mSamplingRates[i];
5810 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005811 }
5812 port->num_sample_rates = i;
5813 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005814 if (mChannelMasks[i] != 0) {
5815 port->channel_masks[i] = mChannelMasks[i];
5816 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005817 }
5818 port->num_channel_masks = i;
5819 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005820 if (mFormats[i] != 0) {
5821 port->formats[i] = mFormats[i];
5822 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005823 }
5824 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005825
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005826 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005827
5828 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5829 port->gains[i] = mGains[i]->mGain;
5830 }
5831 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005832}
5833
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005834void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
5835 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
5836 const uint32_t rate = port->mSamplingRates.itemAt(k);
5837 if (rate != 0) { // skip "dynamic" rates
5838 bool hasRate = false;
5839 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
5840 if (rate == mSamplingRates.itemAt(l)) {
5841 hasRate = true;
5842 break;
5843 }
5844 }
5845 if (!hasRate) { // never import a sampling rate twice
5846 mSamplingRates.add(rate);
5847 }
5848 }
5849 }
5850 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
5851 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
5852 if (mask != 0) { // skip "dynamic" masks
5853 bool hasMask = false;
5854 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
5855 if (mask == mChannelMasks.itemAt(l)) {
5856 hasMask = true;
5857 break;
5858 }
5859 }
5860 if (!hasMask) { // never import a channel mask twice
5861 mChannelMasks.add(mask);
5862 }
5863 }
5864 }
5865 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
5866 const audio_format_t format = port->mFormats.itemAt(k);
5867 if (format != 0) { // skip "dynamic" formats
5868 bool hasFormat = false;
5869 for (size_t l = 0 ; l < mFormats.size() ; l++) {
5870 if (format == mFormats.itemAt(l)) {
5871 hasFormat = true;
5872 break;
5873 }
5874 }
5875 if (!hasFormat) { // never import a channel mask twice
5876 mFormats.add(format);
5877 }
5878 }
5879 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08005880 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
5881 sp<AudioGain> gain = port->mGains.itemAt(k);
5882 if (gain != 0) {
5883 bool hasGain = false;
5884 for (size_t l = 0 ; l < mGains.size() ; l++) {
5885 if (gain == mGains.itemAt(l)) {
5886 hasGain = true;
5887 break;
5888 }
5889 }
5890 if (!hasGain) { // never import a gain twice
5891 mGains.add(gain);
5892 }
5893 }
5894 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005895}
5896
5897void AudioPolicyManager::AudioPort::clearCapabilities() {
5898 mChannelMasks.clear();
5899 mFormats.clear();
5900 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08005901 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005902}
Eric Laurent1c333e22014-05-20 10:48:17 -07005903
5904void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5905{
5906 char *str = strtok(name, "|");
5907
5908 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5909 // rates should be read from the output stream after it is opened for the first time
5910 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5911 mSamplingRates.add(0);
5912 return;
5913 }
5914
5915 while (str != NULL) {
5916 uint32_t rate = atoi(str);
5917 if (rate != 0) {
5918 ALOGV("loadSamplingRates() adding rate %d", rate);
5919 mSamplingRates.add(rate);
5920 }
5921 str = strtok(NULL, "|");
5922 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005923}
5924
5925void AudioPolicyManager::AudioPort::loadFormats(char *name)
5926{
5927 char *str = strtok(name, "|");
5928
5929 // by convention, "0' in the first entry in mFormats indicates the supported formats
5930 // should be read from the output stream after it is opened for the first time
5931 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5932 mFormats.add(AUDIO_FORMAT_DEFAULT);
5933 return;
5934 }
5935
5936 while (str != NULL) {
5937 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5938 ARRAY_SIZE(sFormatNameToEnumTable),
5939 str);
5940 if (format != AUDIO_FORMAT_DEFAULT) {
5941 mFormats.add(format);
5942 }
5943 str = strtok(NULL, "|");
5944 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005945}
5946
5947void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5948{
5949 const char *str = strtok(name, "|");
5950
5951 ALOGV("loadInChannels() %s", name);
5952
5953 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5954 mChannelMasks.add(0);
5955 return;
5956 }
5957
5958 while (str != NULL) {
5959 audio_channel_mask_t channelMask =
5960 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5961 ARRAY_SIZE(sInChannelsNameToEnumTable),
5962 str);
5963 if (channelMask != 0) {
5964 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5965 mChannelMasks.add(channelMask);
5966 }
5967 str = strtok(NULL, "|");
5968 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005969}
5970
5971void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5972{
5973 const char *str = strtok(name, "|");
5974
5975 ALOGV("loadOutChannels() %s", name);
5976
5977 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5978 // masks should be read from the output stream after it is opened for the first time
5979 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5980 mChannelMasks.add(0);
5981 return;
5982 }
5983
5984 while (str != NULL) {
5985 audio_channel_mask_t channelMask =
5986 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5987 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5988 str);
5989 if (channelMask != 0) {
5990 mChannelMasks.add(channelMask);
5991 }
5992 str = strtok(NULL, "|");
5993 }
5994 return;
5995}
5996
Eric Laurent1afeecb2014-05-14 08:52:28 -07005997audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5998{
5999 const char *str = strtok(name, "|");
6000
6001 ALOGV("loadGainMode() %s", name);
6002 audio_gain_mode_t mode = 0;
6003 while (str != NULL) {
6004 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6005 ARRAY_SIZE(sGainModeNameToEnumTable),
6006 str);
6007 str = strtok(NULL, "|");
6008 }
6009 return mode;
6010}
6011
Eric Laurenta121f902014-06-03 13:32:54 -07006012void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006013{
6014 cnode *node = root->first_child;
6015
Eric Laurenta121f902014-06-03 13:32:54 -07006016 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006017
6018 while (node) {
6019 if (strcmp(node->name, GAIN_MODE) == 0) {
6020 gain->mGain.mode = loadGainMode((char *)node->value);
6021 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006022 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006023 gain->mGain.channel_mask =
6024 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6025 ARRAY_SIZE(sInChannelsNameToEnumTable),
6026 (char *)node->value);
6027 } else {
6028 gain->mGain.channel_mask =
6029 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6030 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6031 (char *)node->value);
6032 }
6033 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6034 gain->mGain.min_value = atoi((char *)node->value);
6035 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6036 gain->mGain.max_value = atoi((char *)node->value);
6037 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6038 gain->mGain.default_value = atoi((char *)node->value);
6039 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6040 gain->mGain.step_value = atoi((char *)node->value);
6041 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6042 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6043 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6044 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6045 }
6046 node = node->next;
6047 }
6048
6049 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6050 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6051
6052 if (gain->mGain.mode == 0) {
6053 return;
6054 }
6055 mGains.add(gain);
6056}
6057
6058void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6059{
6060 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006061 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006062 while (node) {
6063 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006064 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006065 node = node->next;
6066 }
6067}
6068
Glenn Kastencbd48022014-07-24 13:46:44 -07006069status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006070{
6071 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6072 if (mSamplingRates[i] == samplingRate) {
6073 return NO_ERROR;
6074 }
6075 }
6076 return BAD_VALUE;
6077}
6078
Glenn Kastencbd48022014-07-24 13:46:44 -07006079status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6080 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006081{
Glenn Kastencbd48022014-07-24 13:46:44 -07006082 // Search for the closest supported sampling rate that is above (preferred)
6083 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6084 // The sampling rates do not need to be sorted in ascending order.
6085 ssize_t maxBelow = -1;
6086 ssize_t minAbove = -1;
6087 uint32_t candidate;
6088 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6089 candidate = mSamplingRates[i];
6090 if (candidate == samplingRate) {
6091 if (updatedSamplingRate != NULL) {
6092 *updatedSamplingRate = candidate;
6093 }
6094 return NO_ERROR;
6095 }
6096 // candidate < desired
6097 if (candidate < samplingRate) {
6098 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6099 maxBelow = i;
6100 }
6101 // candidate > desired
6102 } else {
6103 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6104 minAbove = i;
6105 }
6106 }
6107 }
6108 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6109 // TODO Move these assumptions out.
6110 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6111 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6112 // due to approximation by an int32_t of the
6113 // phase increments
6114 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6115 if (minAbove >= 0) {
6116 candidate = mSamplingRates[minAbove];
6117 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6118 if (updatedSamplingRate != NULL) {
6119 *updatedSamplingRate = candidate;
6120 }
6121 return NO_ERROR;
6122 }
6123 }
6124 // But if we have to up-sample from a lower sampling rate, that's OK.
6125 if (maxBelow >= 0) {
6126 candidate = mSamplingRates[maxBelow];
6127 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6128 if (updatedSamplingRate != NULL) {
6129 *updatedSamplingRate = candidate;
6130 }
6131 return NO_ERROR;
6132 }
6133 }
6134 // leave updatedSamplingRate unmodified
6135 return BAD_VALUE;
6136}
6137
6138status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6139{
6140 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006141 if (mChannelMasks[i] == channelMask) {
6142 return NO_ERROR;
6143 }
6144 }
6145 return BAD_VALUE;
6146}
6147
Glenn Kastencbd48022014-07-24 13:46:44 -07006148status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6149 const
6150{
6151 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6152 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6153 // FIXME Does not handle multi-channel automatic conversions yet
6154 audio_channel_mask_t supported = mChannelMasks[i];
6155 if (supported == channelMask) {
6156 return NO_ERROR;
6157 }
6158 if (isRecordThread) {
6159 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6160 // FIXME Abstract this out to a table.
6161 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6162 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6163 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6164 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6165 return NO_ERROR;
6166 }
6167 }
6168 }
6169 return BAD_VALUE;
6170}
6171
Eric Laurenta121f902014-06-03 13:32:54 -07006172status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6173{
6174 for (size_t i = 0; i < mFormats.size(); i ++) {
6175 if (mFormats[i] == format) {
6176 return NO_ERROR;
6177 }
6178 }
6179 return BAD_VALUE;
6180}
6181
Eric Laurent1e693b52014-07-09 15:03:28 -07006182
6183uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6184{
6185 // special case for uninitialized dynamic profile
6186 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6187 return 0;
6188 }
6189
Eric Laurent828bcff2014-09-07 12:26:06 -07006190 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6191 // channel count / sampling rate combination chosen will be supported by the connected
6192 // sink
6193 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6194 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6195 uint32_t samplingRate = UINT_MAX;
6196 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6197 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6198 samplingRate = mSamplingRates[i];
6199 }
6200 }
6201 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6202 }
6203
Eric Laurent1e693b52014-07-09 15:03:28 -07006204 uint32_t samplingRate = 0;
6205 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6206
6207 // For mixed output and inputs, use max mixer sampling rates. Do not
6208 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006209 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006210 maxRate = UINT_MAX;
6211 }
6212 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6213 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6214 samplingRate = mSamplingRates[i];
6215 }
6216 }
6217 return samplingRate;
6218}
6219
6220audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6221{
6222 // special case for uninitialized dynamic profile
6223 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6224 return AUDIO_CHANNEL_NONE;
6225 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006226 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006227
6228 // For direct outputs, pick minimum channel count: this helps ensuring that the
6229 // channel count / sampling rate combination chosen will be supported by the connected
6230 // sink
6231 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6232 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6233 uint32_t channelCount = UINT_MAX;
6234 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6235 uint32_t cnlCount;
6236 if (mUseInChannelMask) {
6237 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6238 } else {
6239 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6240 }
6241 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6242 channelMask = mChannelMasks[i];
6243 channelCount = cnlCount;
6244 }
6245 }
6246 return channelMask;
6247 }
6248
Eric Laurent1e693b52014-07-09 15:03:28 -07006249 uint32_t channelCount = 0;
6250 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6251
6252 // For mixed output and inputs, use max mixer channel count. Do not
6253 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006254 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006255 maxCount = UINT_MAX;
6256 }
6257 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6258 uint32_t cnlCount;
6259 if (mUseInChannelMask) {
6260 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6261 } else {
6262 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6263 }
6264 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6265 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006266 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006267 }
6268 }
6269 return channelMask;
6270}
6271
Andy Hung9a605382014-07-28 16:16:31 -07006272/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006273const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6274 AUDIO_FORMAT_DEFAULT,
6275 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006276 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006277 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006278 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006279 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006280};
6281
6282int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6283 audio_format_t format2)
6284{
6285 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6286 // compressed format and better than any PCM format. This is by design of pickFormat()
6287 if (!audio_is_linear_pcm(format1)) {
6288 if (!audio_is_linear_pcm(format2)) {
6289 return 0;
6290 }
6291 return 1;
6292 }
6293 if (!audio_is_linear_pcm(format2)) {
6294 return -1;
6295 }
6296
6297 int index1 = -1, index2 = -1;
6298 for (size_t i = 0;
6299 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6300 i ++) {
6301 if (sPcmFormatCompareTable[i] == format1) {
6302 index1 = i;
6303 }
6304 if (sPcmFormatCompareTable[i] == format2) {
6305 index2 = i;
6306 }
6307 }
6308 // format1 not found => index1 < 0 => format2 > format1
6309 // format2 not found => index2 < 0 => format2 < format1
6310 return index1 - index2;
6311}
6312
6313audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6314{
6315 // special case for uninitialized dynamic profile
6316 if (mFormats.size() == 1 && mFormats[0] == 0) {
6317 return AUDIO_FORMAT_DEFAULT;
6318 }
6319
6320 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006321 audio_format_t bestFormat =
6322 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6323 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006324 // For mixed output and inputs, use best mixer output format. Do not
6325 // limit format otherwise
6326 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6327 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006328 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006329 bestFormat = AUDIO_FORMAT_INVALID;
6330 }
6331
6332 for (size_t i = 0; i < mFormats.size(); i ++) {
6333 if ((compareFormats(mFormats[i], format) > 0) &&
6334 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6335 format = mFormats[i];
6336 }
6337 }
6338 return format;
6339}
6340
Eric Laurenta121f902014-06-03 13:32:54 -07006341status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6342 int index) const
6343{
6344 if (index < 0 || (size_t)index >= mGains.size()) {
6345 return BAD_VALUE;
6346 }
6347 return mGains[index]->checkConfig(gainConfig);
6348}
6349
Eric Laurent1afeecb2014-05-14 08:52:28 -07006350void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6351{
6352 const size_t SIZE = 256;
6353 char buffer[SIZE];
6354 String8 result;
6355
6356 if (mName.size() != 0) {
6357 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6358 result.append(buffer);
6359 }
6360
6361 if (mSamplingRates.size() != 0) {
6362 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6363 result.append(buffer);
6364 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006365 if (i == 0 && mSamplingRates[i] == 0) {
6366 snprintf(buffer, SIZE, "Dynamic");
6367 } else {
6368 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6369 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006370 result.append(buffer);
6371 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6372 }
6373 result.append("\n");
6374 }
6375
6376 if (mChannelMasks.size() != 0) {
6377 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6378 result.append(buffer);
6379 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006380 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6381
6382 if (i == 0 && mChannelMasks[i] == 0) {
6383 snprintf(buffer, SIZE, "Dynamic");
6384 } else {
6385 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6386 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006387 result.append(buffer);
6388 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6389 }
6390 result.append("\n");
6391 }
6392
6393 if (mFormats.size() != 0) {
6394 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6395 result.append(buffer);
6396 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006397 const char *formatStr = enumToString(sFormatNameToEnumTable,
6398 ARRAY_SIZE(sFormatNameToEnumTable),
6399 mFormats[i]);
6400 if (i == 0 && strcmp(formatStr, "") == 0) {
6401 snprintf(buffer, SIZE, "Dynamic");
6402 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006403 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006404 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006405 result.append(buffer);
6406 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6407 }
6408 result.append("\n");
6409 }
6410 write(fd, result.string(), result.size());
6411 if (mGains.size() != 0) {
6412 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6413 write(fd, buffer, strlen(buffer) + 1);
6414 result.append(buffer);
6415 for (size_t i = 0; i < mGains.size(); i++) {
6416 mGains[i]->dump(fd, spaces + 2, i);
6417 }
6418 }
6419}
6420
6421// --- AudioGain class implementation
6422
Eric Laurenta121f902014-06-03 13:32:54 -07006423AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006424{
Eric Laurenta121f902014-06-03 13:32:54 -07006425 mIndex = index;
6426 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006427 memset(&mGain, 0, sizeof(struct audio_gain));
6428}
6429
Eric Laurenta121f902014-06-03 13:32:54 -07006430void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6431{
6432 config->index = mIndex;
6433 config->mode = mGain.mode;
6434 config->channel_mask = mGain.channel_mask;
6435 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6436 config->values[0] = mGain.default_value;
6437 } else {
6438 uint32_t numValues;
6439 if (mUseInChannelMask) {
6440 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6441 } else {
6442 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6443 }
6444 for (size_t i = 0; i < numValues; i++) {
6445 config->values[i] = mGain.default_value;
6446 }
6447 }
6448 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6449 config->ramp_duration_ms = mGain.min_ramp_ms;
6450 }
6451}
6452
6453status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6454{
6455 if ((config->mode & ~mGain.mode) != 0) {
6456 return BAD_VALUE;
6457 }
6458 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6459 if ((config->values[0] < mGain.min_value) ||
6460 (config->values[0] > mGain.max_value)) {
6461 return BAD_VALUE;
6462 }
6463 } else {
6464 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6465 return BAD_VALUE;
6466 }
6467 uint32_t numValues;
6468 if (mUseInChannelMask) {
6469 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6470 } else {
6471 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6472 }
6473 for (size_t i = 0; i < numValues; i++) {
6474 if ((config->values[i] < mGain.min_value) ||
6475 (config->values[i] > mGain.max_value)) {
6476 return BAD_VALUE;
6477 }
6478 }
6479 }
6480 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6481 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6482 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6483 return BAD_VALUE;
6484 }
6485 }
6486 return NO_ERROR;
6487}
6488
Eric Laurent1afeecb2014-05-14 08:52:28 -07006489void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6490{
6491 const size_t SIZE = 256;
6492 char buffer[SIZE];
6493 String8 result;
6494
6495 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6496 result.append(buffer);
6497 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6498 result.append(buffer);
6499 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6500 result.append(buffer);
6501 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6502 result.append(buffer);
6503 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6504 result.append(buffer);
6505 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6506 result.append(buffer);
6507 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6508 result.append(buffer);
6509 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6510 result.append(buffer);
6511 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6512 result.append(buffer);
6513
6514 write(fd, result.string(), result.size());
6515}
6516
Eric Laurent1f2f2232014-06-02 12:01:23 -07006517// --- AudioPortConfig class implementation
6518
6519AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6520{
6521 mSamplingRate = 0;
6522 mChannelMask = AUDIO_CHANNEL_NONE;
6523 mFormat = AUDIO_FORMAT_INVALID;
6524 mGain.index = -1;
6525}
6526
Eric Laurenta121f902014-06-03 13:32:54 -07006527status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6528 const struct audio_port_config *config,
6529 struct audio_port_config *backupConfig)
6530{
6531 struct audio_port_config localBackupConfig;
6532 status_t status = NO_ERROR;
6533
6534 localBackupConfig.config_mask = config->config_mask;
6535 toAudioPortConfig(&localBackupConfig);
6536
Marco Nelissen961ec212014-08-25 15:58:39 -07006537 sp<AudioPort> audioport = getAudioPort();
6538 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006539 status = NO_INIT;
6540 goto exit;
6541 }
6542 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006543 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006544 if (status != NO_ERROR) {
6545 goto exit;
6546 }
6547 mSamplingRate = config->sample_rate;
6548 }
6549 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006550 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006551 if (status != NO_ERROR) {
6552 goto exit;
6553 }
6554 mChannelMask = config->channel_mask;
6555 }
6556 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006557 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006558 if (status != NO_ERROR) {
6559 goto exit;
6560 }
6561 mFormat = config->format;
6562 }
6563 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006564 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006565 if (status != NO_ERROR) {
6566 goto exit;
6567 }
6568 mGain = config->gain;
6569 }
6570
6571exit:
6572 if (status != NO_ERROR) {
6573 applyAudioPortConfig(&localBackupConfig);
6574 }
6575 if (backupConfig != NULL) {
6576 *backupConfig = localBackupConfig;
6577 }
6578 return status;
6579}
6580
Eric Laurent1f2f2232014-06-02 12:01:23 -07006581void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6582 struct audio_port_config *dstConfig,
6583 const struct audio_port_config *srcConfig) const
6584{
6585 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6586 dstConfig->sample_rate = mSamplingRate;
6587 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6588 dstConfig->sample_rate = srcConfig->sample_rate;
6589 }
6590 } else {
6591 dstConfig->sample_rate = 0;
6592 }
6593 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6594 dstConfig->channel_mask = mChannelMask;
6595 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6596 dstConfig->channel_mask = srcConfig->channel_mask;
6597 }
6598 } else {
6599 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6600 }
6601 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6602 dstConfig->format = mFormat;
6603 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6604 dstConfig->format = srcConfig->format;
6605 }
6606 } else {
6607 dstConfig->format = AUDIO_FORMAT_INVALID;
6608 }
6609 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6610 dstConfig->gain = mGain;
6611 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6612 dstConfig->gain = srcConfig->gain;
6613 }
6614 } else {
6615 dstConfig->gain.index = -1;
6616 }
6617 if (dstConfig->gain.index != -1) {
6618 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6619 } else {
6620 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6621 }
6622}
6623
Eric Laurent1c333e22014-05-20 10:48:17 -07006624// --- IOProfile class implementation
6625
Eric Laurent1afeecb2014-05-14 08:52:28 -07006626AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006627 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006628 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006629{
6630}
6631
Eric Laurente0720872014-03-11 09:30:41 -07006632AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006633{
6634}
6635
6636// checks if the IO profile is compatible with specified parameters.
6637// Sampling rate, format and channel mask must be specified in order to
6638// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006639bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006640 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006641 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006642 audio_format_t format,
6643 audio_channel_mask_t channelMask,
Eric Laurent5dbe4712014-09-19 19:04:57 -07006644 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07006645{
Glenn Kastencbd48022014-07-24 13:46:44 -07006646 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6647 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6648 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006649
Glenn Kastencbd48022014-07-24 13:46:44 -07006650 if ((mSupportedDevices.types() & device) != device) {
6651 return false;
6652 }
6653
6654 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006655 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006656 }
6657 uint32_t myUpdatedSamplingRate = samplingRate;
6658 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006659 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006660 }
6661 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6662 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006663 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006664 }
6665
6666 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6667 return false;
6668 }
6669
6670 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6671 checkExactChannelMask(channelMask) != NO_ERROR)) {
6672 return false;
6673 }
6674 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6675 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6676 return false;
6677 }
6678
6679 if (isPlaybackThread && (mFlags & flags) != flags) {
6680 return false;
6681 }
6682 // The only input flag that is allowed to be different is the fast flag.
6683 // An existing fast stream is compatible with a normal track request.
6684 // An existing normal stream is compatible with a fast track request,
6685 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07006686 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07006687 ~AUDIO_INPUT_FLAG_FAST)) {
6688 return false;
6689 }
6690
6691 if (updatedSamplingRate != NULL) {
6692 *updatedSamplingRate = myUpdatedSamplingRate;
6693 }
6694 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006695}
6696
Eric Laurente0720872014-03-11 09:30:41 -07006697void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006698{
6699 const size_t SIZE = 256;
6700 char buffer[SIZE];
6701 String8 result;
6702
Eric Laurent1afeecb2014-05-14 08:52:28 -07006703 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006704
Eric Laurente552edb2014-03-10 17:42:56 -07006705 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6706 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006707 snprintf(buffer, SIZE, " - devices:\n");
6708 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006709 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006710 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6711 mSupportedDevices[i]->dump(fd, 6, i);
6712 }
Eric Laurente552edb2014-03-10 17:42:56 -07006713}
6714
Eric Laurentd4692962014-05-05 18:13:44 -07006715void AudioPolicyManager::IOProfile::log()
6716{
6717 const size_t SIZE = 256;
6718 char buffer[SIZE];
6719 String8 result;
6720
6721 ALOGV(" - sampling rates: ");
6722 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6723 ALOGV(" %d", mSamplingRates[i]);
6724 }
6725
6726 ALOGV(" - channel masks: ");
6727 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6728 ALOGV(" 0x%04x", mChannelMasks[i]);
6729 }
6730
6731 ALOGV(" - formats: ");
6732 for (size_t i = 0; i < mFormats.size(); i++) {
6733 ALOGV(" 0x%08x", mFormats[i]);
6734 }
6735
6736 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6737 ALOGV(" - flags: 0x%04x\n", mFlags);
6738}
6739
6740
Eric Laurent3a4311c2014-03-17 12:00:47 -07006741// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006742
Eric Laurent1f2f2232014-06-02 12:01:23 -07006743
6744AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6745 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6746 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6747 AUDIO_PORT_ROLE_SOURCE,
6748 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006749 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006750{
Eric Laurenta121f902014-06-03 13:32:54 -07006751 if (mGains.size() > 0) {
6752 mGains[0]->getDefaultConfig(&mGain);
6753 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006754}
6755
Eric Laurent3a4311c2014-03-17 12:00:47 -07006756bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006757{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006758 // Devices are considered equal if they:
6759 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6760 // - have the same address or one device does not specify the address
6761 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006762 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006763 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006764 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006765 mChannelMask == other->mChannelMask);
6766}
6767
6768void AudioPolicyManager::DeviceVector::refreshTypes()
6769{
Eric Laurent1c333e22014-05-20 10:48:17 -07006770 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006771 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006772 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006773 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006774 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006775}
6776
6777ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6778{
6779 for(size_t i = 0; i < size(); i++) {
6780 if (item->equals(itemAt(i))) {
6781 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006782 }
6783 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006784 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006785}
6786
Eric Laurent3a4311c2014-03-17 12:00:47 -07006787ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006788{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006789 ssize_t ret = indexOf(item);
6790
6791 if (ret < 0) {
6792 ret = SortedVector::add(item);
6793 if (ret >= 0) {
6794 refreshTypes();
6795 }
6796 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006797 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006798 ret = -1;
6799 }
6800 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006801}
6802
Eric Laurent3a4311c2014-03-17 12:00:47 -07006803ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6804{
6805 size_t i;
6806 ssize_t ret = indexOf(item);
6807
6808 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006809 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006810 } else {
6811 ret = SortedVector::removeAt(ret);
6812 if (ret >= 0) {
6813 refreshTypes();
6814 }
6815 }
6816 return ret;
6817}
6818
6819void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6820{
6821 DeviceVector deviceList;
6822
6823 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6824 types &= ~role_bit;
6825
6826 while (types) {
6827 uint32_t i = 31 - __builtin_clz(types);
6828 uint32_t type = 1 << i;
6829 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006830 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006831 }
6832}
6833
Eric Laurent1afeecb2014-05-14 08:52:28 -07006834void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6835 const DeviceVector& declaredDevices)
6836{
6837 char *devName = strtok(name, "|");
6838 while (devName != NULL) {
6839 if (strlen(devName) != 0) {
6840 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6841 ARRAY_SIZE(sDeviceNameToEnumTable),
6842 devName);
6843 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07006844 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
6845 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
6846 dev->mAddress = String8("0");
6847 }
6848 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006849 } else {
6850 sp<DeviceDescriptor> deviceDesc =
6851 declaredDevices.getDeviceFromName(String8(devName));
6852 if (deviceDesc != 0) {
6853 add(deviceDesc);
6854 }
6855 }
6856 }
6857 devName = strtok(NULL, "|");
6858 }
6859}
6860
Eric Laurent1c333e22014-05-20 10:48:17 -07006861sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6862 audio_devices_t type, String8 address) const
6863{
6864 sp<DeviceDescriptor> device;
6865 for (size_t i = 0; i < size(); i++) {
6866 if (itemAt(i)->mDeviceType == type) {
6867 device = itemAt(i);
6868 if (itemAt(i)->mAddress = address) {
6869 break;
6870 }
6871 }
6872 }
6873 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6874 type, address.string(), device.get());
6875 return device;
6876}
6877
Eric Laurent6a94d692014-05-20 11:18:06 -07006878sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6879 audio_port_handle_t id) const
6880{
6881 sp<DeviceDescriptor> device;
6882 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006883 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006884 if (itemAt(i)->mId == id) {
6885 device = itemAt(i);
6886 break;
6887 }
6888 }
6889 return device;
6890}
6891
Eric Laurent1c333e22014-05-20 10:48:17 -07006892AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6893 audio_devices_t type) const
6894{
6895 DeviceVector devices;
6896 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6897 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6898 devices.add(itemAt(i));
6899 type &= ~itemAt(i)->mDeviceType;
6900 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6901 itemAt(i)->mDeviceType, itemAt(i).get());
6902 }
6903 }
6904 return devices;
6905}
6906
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006907AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6908 audio_devices_t type, String8 address) const
6909{
6910 DeviceVector devices;
6911 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6912 for (size_t i = 0; i < size(); i++) {
6913 //ALOGV(" at i=%d: device=%x, addr=%s",
6914 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6915 if (itemAt(i)->mDeviceType == type) {
6916 if (itemAt(i)->mAddress == address) {
6917 //ALOGV(" found matching address %s", address.string());
6918 devices.add(itemAt(i));
6919 }
6920 }
6921 }
6922 return devices;
6923}
6924
Eric Laurent1afeecb2014-05-14 08:52:28 -07006925sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6926 const String8& name) const
6927{
6928 sp<DeviceDescriptor> device;
6929 for (size_t i = 0; i < size(); i++) {
6930 if (itemAt(i)->mName == name) {
6931 device = itemAt(i);
6932 break;
6933 }
6934 }
6935 return device;
6936}
6937
Eric Laurent6a94d692014-05-20 11:18:06 -07006938void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6939 struct audio_port_config *dstConfig,
6940 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006941{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006942 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6943 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006944 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006945 }
6946
6947 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6948
Eric Laurent6a94d692014-05-20 11:18:06 -07006949 dstConfig->id = mId;
6950 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006951 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006952 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006953 dstConfig->ext.device.type = mDeviceType;
6954 dstConfig->ext.device.hw_module = mModule->mHandle;
6955 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006956}
6957
6958void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6959{
Eric Laurent83b88082014-06-20 18:31:16 -07006960 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006961 AudioPort::toAudioPort(port);
6962 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006963 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006964 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006965 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006966 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6967}
6968
Eric Laurent1afeecb2014-05-14 08:52:28 -07006969status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006970{
6971 const size_t SIZE = 256;
6972 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006973 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006974
Eric Laurent1afeecb2014-05-14 08:52:28 -07006975 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6976 result.append(buffer);
6977 if (mId != 0) {
6978 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6979 result.append(buffer);
6980 }
6981 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6982 enumToString(sDeviceNameToEnumTable,
6983 ARRAY_SIZE(sDeviceNameToEnumTable),
6984 mDeviceType));
6985 result.append(buffer);
6986 if (mAddress.size() != 0) {
6987 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6988 result.append(buffer);
6989 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006990 write(fd, result.string(), result.size());
6991 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006992
6993 return NO_ERROR;
6994}
6995
Eric Laurent4d416952014-08-10 14:07:09 -07006996status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
6997{
6998 const size_t SIZE = 256;
6999 char buffer[SIZE];
7000 String8 result;
7001
7002
7003 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7004 result.append(buffer);
7005 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7006 result.append(buffer);
7007 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7008 result.append(buffer);
7009 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7010 result.append(buffer);
7011 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7012 result.append(buffer);
7013 for (size_t i = 0; i < mPatch.num_sources; i++) {
7014 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7015 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7016 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7017 ARRAY_SIZE(sDeviceNameToEnumTable),
7018 mPatch.sources[i].ext.device.type));
7019 } else {
7020 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7021 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7022 }
7023 result.append(buffer);
7024 }
7025 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7026 result.append(buffer);
7027 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7028 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7029 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7030 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7031 ARRAY_SIZE(sDeviceNameToEnumTable),
7032 mPatch.sinks[i].ext.device.type));
7033 } else {
7034 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7035 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7036 }
7037 result.append(buffer);
7038 }
7039
7040 write(fd, result.string(), result.size());
7041 return NO_ERROR;
7042}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007043
7044// --- audio_policy.conf file parsing
7045
Eric Laurent5dbe4712014-09-19 19:04:57 -07007046uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007047{
7048 uint32_t flag = 0;
7049
7050 // it is OK to cast name to non const here as we are not going to use it after
7051 // strtok() modifies it
7052 char *flagName = strtok(name, "|");
7053 while (flagName != NULL) {
7054 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007055 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7056 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007057 flagName);
7058 }
7059 flagName = strtok(NULL, "|");
7060 }
7061 //force direct flag if offload flag is set: offloading implies a direct output stream
7062 // and all common behaviors are driven by checking only the direct flag
7063 // this should normally be set appropriately in the policy configuration file
7064 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7065 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7066 }
7067
Eric Laurent5dbe4712014-09-19 19:04:57 -07007068 return flag;
7069}
7070
7071uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7072{
7073 uint32_t flag = 0;
7074
7075 // it is OK to cast name to non const here as we are not going to use it after
7076 // strtok() modifies it
7077 char *flagName = strtok(name, "|");
7078 while (flagName != NULL) {
7079 if (strlen(flagName) != 0) {
7080 flag |= stringToEnum(sInputFlagNameToEnumTable,
7081 ARRAY_SIZE(sInputFlagNameToEnumTable),
7082 flagName);
7083 }
7084 flagName = strtok(NULL, "|");
7085 }
7086 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007087}
7088
Eric Laurente0720872014-03-11 09:30:41 -07007089audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007090{
7091 uint32_t device = 0;
7092
7093 char *devName = strtok(name, "|");
7094 while (devName != NULL) {
7095 if (strlen(devName) != 0) {
7096 device |= stringToEnum(sDeviceNameToEnumTable,
7097 ARRAY_SIZE(sDeviceNameToEnumTable),
7098 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007099 }
Eric Laurente552edb2014-03-10 17:42:56 -07007100 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007101 }
Eric Laurente552edb2014-03-10 17:42:56 -07007102 return device;
7103}
7104
Eric Laurente0720872014-03-11 09:30:41 -07007105void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007106{
Eric Laurente552edb2014-03-10 17:42:56 -07007107 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007108 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007109 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007110
Eric Laurent1afeecb2014-05-14 08:52:28 -07007111 node = config_find(root, DEVICES_TAG);
7112 if (node != NULL) {
7113 node = node->first_child;
7114 while (node) {
7115 ALOGV("loadHwModule() loading device %s", node->name);
7116 status_t tmpStatus = module->loadDevice(node);
7117 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7118 status = tmpStatus;
7119 }
7120 node = node->next;
7121 }
7122 }
7123 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007124 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007125 node = node->first_child;
7126 while (node) {
7127 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007128 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007129 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7130 status = tmpStatus;
7131 }
7132 node = node->next;
7133 }
7134 }
7135 node = config_find(root, INPUTS_TAG);
7136 if (node != NULL) {
7137 node = node->first_child;
7138 while (node) {
7139 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007140 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007141 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7142 status = tmpStatus;
7143 }
7144 node = node->next;
7145 }
7146 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007147 loadGlobalConfig(root, module);
7148
Eric Laurente552edb2014-03-10 17:42:56 -07007149 if (status == NO_ERROR) {
7150 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007151 }
7152}
7153
Eric Laurente0720872014-03-11 09:30:41 -07007154void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007155{
7156 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7157 if (node == NULL) {
7158 return;
7159 }
7160
7161 node = node->first_child;
7162 while (node) {
7163 ALOGV("loadHwModules() loading module %s", node->name);
7164 loadHwModule(node);
7165 node = node->next;
7166 }
7167}
7168
Eric Laurent1f2f2232014-06-02 12:01:23 -07007169void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007170{
7171 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007172
Eric Laurente552edb2014-03-10 17:42:56 -07007173 if (node == NULL) {
7174 return;
7175 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007176 DeviceVector declaredDevices;
7177 if (module != NULL) {
7178 declaredDevices = module->mDeclaredDevices;
7179 }
7180
Eric Laurente552edb2014-03-10 17:42:56 -07007181 node = node->first_child;
7182 while (node) {
7183 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007184 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7185 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007186 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7187 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007188 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007189 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007190 ARRAY_SIZE(sDeviceNameToEnumTable),
7191 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007192 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007193 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007194 } else {
7195 ALOGW("loadGlobalConfig() default device not specified");
7196 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007197 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007198 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007199 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7200 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007201 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007202 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7203 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7204 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007205 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7206 uint32_t major, minor;
7207 sscanf((char *)node->value, "%u.%u", &major, &minor);
7208 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7209 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7210 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007211 }
7212 node = node->next;
7213 }
7214}
7215
Eric Laurente0720872014-03-11 09:30:41 -07007216status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007217{
7218 cnode *root;
7219 char *data;
7220
7221 data = (char *)load_file(path, NULL);
7222 if (data == NULL) {
7223 return -ENODEV;
7224 }
7225 root = config_node("", "");
7226 config_load(root, data);
7227
Eric Laurente552edb2014-03-10 17:42:56 -07007228 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007229 // legacy audio_policy.conf files have one global_configuration section
7230 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007231 config_free(root);
7232 free(root);
7233 free(data);
7234
7235 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7236
7237 return NO_ERROR;
7238}
7239
Eric Laurente0720872014-03-11 09:30:41 -07007240void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007241{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007242 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007243 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007244 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7245 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007246 mAvailableOutputDevices.add(mDefaultOutputDevice);
7247 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007248
7249 module = new HwModule("primary");
7250
Eric Laurent1afeecb2014-05-14 08:52:28 -07007251 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007252 profile->mSamplingRates.add(44100);
7253 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7254 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007255 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007256 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7257 module->mOutputProfiles.add(profile);
7258
Eric Laurent1afeecb2014-05-14 08:52:28 -07007259 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007260 profile->mSamplingRates.add(8000);
7261 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7262 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007263 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007264 module->mInputProfiles.add(profile);
7265
7266 mHwModules.add(module);
7267}
7268
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007269audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7270{
7271 // flags to stream type mapping
7272 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7273 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7274 }
7275 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7276 return AUDIO_STREAM_BLUETOOTH_SCO;
7277 }
7278
7279 // usage to stream type mapping
7280 switch (attr->usage) {
7281 case AUDIO_USAGE_MEDIA:
7282 case AUDIO_USAGE_GAME:
7283 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7284 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7285 return AUDIO_STREAM_MUSIC;
7286 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7287 return AUDIO_STREAM_SYSTEM;
7288 case AUDIO_USAGE_VOICE_COMMUNICATION:
7289 return AUDIO_STREAM_VOICE_CALL;
7290
7291 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7292 return AUDIO_STREAM_DTMF;
7293
7294 case AUDIO_USAGE_ALARM:
7295 return AUDIO_STREAM_ALARM;
7296 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7297 return AUDIO_STREAM_RING;
7298
7299 case AUDIO_USAGE_NOTIFICATION:
7300 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7301 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7302 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7303 case AUDIO_USAGE_NOTIFICATION_EVENT:
7304 return AUDIO_STREAM_NOTIFICATION;
7305
7306 case AUDIO_USAGE_UNKNOWN:
7307 default:
7308 return AUDIO_STREAM_MUSIC;
7309 }
7310}
Eric Laurente552edb2014-03-10 17:42:56 -07007311}; // namespace android