blob: fff77462d3b5831afdc57108fca62d9dbb2525e0 [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
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001130 // cannot start playback of STREAM_TTS if any other output is being used
1131 uint32_t beaconMuteLatency = 0;
1132 if (stream == AUDIO_STREAM_TTS) {
1133 ALOGV("\t found BEACON stream");
1134 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1135 return INVALID_OPERATION;
1136 } else {
1137 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1138 }
1139 } else {
1140 // some playback other than beacon starts
1141 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1142 }
1143
Eric Laurent1f2f2232014-06-02 12:01:23 -07001144 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001145
1146 // increment usage count for this stream on the requested output:
1147 // NOTE that the usage count is the same for duplicated output and hardware output which is
1148 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1149 outputDesc->changeRefCount(stream, 1);
1150
1151 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001152 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001153 routing_strategy strategy = getStrategy(stream);
1154 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001155 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1156 (beaconMuteLatency > 0);
1157 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001158 bool force = false;
1159 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001160 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001161 if (desc != outputDesc) {
1162 // force a device change if any other output is managed by the same hw
1163 // module and has a current device selection that differs from selected device.
1164 // In this case, the audio HAL must receive the new device selection so that it can
1165 // change the device currently selected by the other active output.
1166 if (outputDesc->sharesHwModuleWith(desc) &&
1167 desc->device() != newDevice) {
1168 force = true;
1169 }
1170 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001171 // a notification so that audio focus effect can propagate, or that a mute/unmute
1172 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001173 uint32_t latency = desc->latency();
1174 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1175 waitMs = latency;
1176 }
1177 }
1178 }
1179 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1180
1181 // handle special case for sonification while in call
1182 if (isInCall()) {
1183 handleIncallSonification(stream, true, false);
1184 }
1185
1186 // apply volume rules for current stream and device if necessary
1187 checkAndSetVolume(stream,
1188 mStreams[stream].getVolumeIndex(newDevice),
1189 output,
1190 newDevice);
1191
1192 // update the outputs if starting an output with a stream that can affect notification
1193 // routing
1194 handleNotificationRoutingForStream(stream);
1195 if (waitMs > muteWaitMs) {
1196 usleep((waitMs - muteWaitMs) * 2 * 1000);
1197 }
1198 }
1199 return NO_ERROR;
1200}
1201
1202
Eric Laurente0720872014-03-11 09:30:41 -07001203status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001204 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001205 int session)
1206{
1207 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1208 ssize_t index = mOutputs.indexOfKey(output);
1209 if (index < 0) {
1210 ALOGW("stopOutput() unknown output %d", output);
1211 return BAD_VALUE;
1212 }
1213
Eric Laurent1f2f2232014-06-02 12:01:23 -07001214 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001215
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001216 // always handle stream stop, check which stream type is stopping
1217 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1218
Eric Laurente552edb2014-03-10 17:42:56 -07001219 // handle special case for sonification while in call
1220 if (isInCall()) {
1221 handleIncallSonification(stream, false, false);
1222 }
1223
1224 if (outputDesc->mRefCount[stream] > 0) {
1225 // decrement usage count of this stream on the output
1226 outputDesc->changeRefCount(stream, -1);
1227 // store time at which the stream was stopped - see isStreamActive()
1228 if (outputDesc->mRefCount[stream] == 0) {
1229 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001230 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001231 // delay the device switch by twice the latency because stopOutput() is executed when
1232 // the track stop() command is received and at that time the audio track buffer can
1233 // still contain data that needs to be drained. The latency only covers the audio HAL
1234 // and kernel buffers. Also the latency does not always include additional delay in the
1235 // audio path (audio DSP, CODEC ...)
1236 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1237
1238 // force restoring the device selection on other active outputs if it differs from the
1239 // one being selected for this output
1240 for (size_t i = 0; i < mOutputs.size(); i++) {
1241 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001242 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001243 if (curOutput != output &&
1244 desc->isActive() &&
1245 outputDesc->sharesHwModuleWith(desc) &&
1246 (newDevice != desc->device())) {
1247 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001248 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001249 true,
1250 outputDesc->mLatency*2);
1251 }
1252 }
1253 // update the outputs if stopping one with a stream that can affect notification routing
1254 handleNotificationRoutingForStream(stream);
1255 }
1256 return NO_ERROR;
1257 } else {
1258 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1259 return INVALID_OPERATION;
1260 }
1261}
1262
Eric Laurente0720872014-03-11 09:30:41 -07001263void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001264{
1265 ALOGV("releaseOutput() %d", output);
1266 ssize_t index = mOutputs.indexOfKey(output);
1267 if (index < 0) {
1268 ALOGW("releaseOutput() releasing unknown output %d", output);
1269 return;
1270 }
1271
1272#ifdef AUDIO_POLICY_TEST
1273 int testIndex = testOutputIndex(output);
1274 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001275 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001276 if (outputDesc->isActive()) {
1277 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001278 mOutputs.removeItem(output);
1279 mTestOutputs[testIndex] = 0;
1280 }
1281 return;
1282 }
1283#endif //AUDIO_POLICY_TEST
1284
Eric Laurent1f2f2232014-06-02 12:01:23 -07001285 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001286 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001287 if (desc->mDirectOpenCount <= 0) {
1288 ALOGW("releaseOutput() invalid open count %d for output %d",
1289 desc->mDirectOpenCount, output);
1290 return;
1291 }
1292 if (--desc->mDirectOpenCount == 0) {
1293 closeOutput(output);
1294 // If effects where present on the output, audioflinger moved them to the primary
1295 // output by default: move them back to the appropriate output.
1296 audio_io_handle_t dstOutput = getOutputForEffect();
1297 if (dstOutput != mPrimaryOutput) {
1298 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1299 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001300 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001301 }
1302 }
1303}
1304
1305
Eric Laurente0720872014-03-11 09:30:41 -07001306audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001307 uint32_t samplingRate,
1308 audio_format_t format,
1309 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001310 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001311 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001312{
Eric Laurent4dc68062014-07-28 17:26:49 -07001313 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001314 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001315 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001316
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001317 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001318
1319 if (device == AUDIO_DEVICE_NONE) {
1320 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001321 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001322 }
1323
1324 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001325 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001326 case AUDIO_SOURCE_VOICE_UPLINK:
1327 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1328 break;
1329 case AUDIO_SOURCE_VOICE_DOWNLINK:
1330 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1331 break;
1332 case AUDIO_SOURCE_VOICE_CALL:
1333 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1334 break;
1335 default:
1336 break;
1337 }
1338
Eric Laurent5dbe4712014-09-19 19:04:57 -07001339 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1340 bool isSoundTrigger = false;
1341 audio_source_t halInputSource = inputSource;
1342 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1343 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1344 if (index >= 0) {
1345 input = mSoundTriggerSessions.valueFor(session);
1346 isSoundTrigger = true;
1347 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1348 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1349 } else {
1350 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1351 }
1352 }
1353
Eric Laurent1c333e22014-05-20 10:48:17 -07001354 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001355 samplingRate,
1356 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001357 channelMask,
1358 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001359 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001360 //retry without flags
1361 audio_input_flags_t log_flags = flags;
1362 flags = AUDIO_INPUT_FLAG_NONE;
1363 profile = getInputProfile(device,
1364 samplingRate,
1365 format,
1366 channelMask,
1367 flags);
1368 if (profile == 0) {
1369 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1370 "channelMask 0x%X, flags %#x",
1371 device, samplingRate, format, channelMask, log_flags);
1372 return AUDIO_IO_HANDLE_NONE;
1373 }
Eric Laurente552edb2014-03-10 17:42:56 -07001374 }
1375
1376 if (profile->mModule->mHandle == 0) {
1377 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001378 return AUDIO_IO_HANDLE_NONE;
1379 }
1380
1381 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1382 config.sample_rate = samplingRate;
1383 config.channel_mask = channelMask;
1384 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001385
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001386 // handle legacy remote submix case where the address was not always specified
1387 String8 address = deviceDistinguishesOnAddress(device) ? String8("0") : String8("");
1388
Eric Laurentcf2c0212014-07-25 16:20:43 -07001389 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1390 &input,
1391 &config,
1392 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001393 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001394 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001395 flags);
1396
1397 // only accept input with the exact requested set of parameters
1398 if (status != NO_ERROR ||
1399 (samplingRate != config.sample_rate) ||
1400 (format != config.format) ||
1401 (channelMask != config.channel_mask)) {
1402 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1403 samplingRate, format, channelMask);
1404 if (input != AUDIO_IO_HANDLE_NONE) {
1405 mpClientInterface->closeInput(input);
1406 }
1407 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001408 }
1409
Eric Laurent1f2f2232014-06-02 12:01:23 -07001410 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001411 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001412 inputDesc->mRefCount = 0;
1413 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001414 inputDesc->mSamplingRate = samplingRate;
1415 inputDesc->mFormat = format;
1416 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001417 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001418 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001419 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001420
Eric Laurentd4692962014-05-05 18:13:44 -07001421 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001422 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001423 return input;
1424}
1425
Eric Laurent4dc68062014-07-28 17:26:49 -07001426status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1427 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001428{
1429 ALOGV("startInput() input %d", input);
1430 ssize_t index = mInputs.indexOfKey(input);
1431 if (index < 0) {
1432 ALOGW("startInput() unknown input %d", input);
1433 return BAD_VALUE;
1434 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001435 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001436
Eric Laurent4dc68062014-07-28 17:26:49 -07001437 index = inputDesc->mSessions.indexOf(session);
1438 if (index < 0) {
1439 ALOGW("startInput() unknown session %d on input %d", session, input);
1440 return BAD_VALUE;
1441 }
1442
Glenn Kasten74a8e252014-07-24 14:09:55 -07001443 // virtual input devices are compatible with other input devices
1444 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1445
1446 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001447 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001448 if (activeInput != 0 && activeInput != input) {
1449
1450 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1451 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001452 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001453 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001454 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001455 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1456 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001457 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001458 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001459 return INVALID_OPERATION;
1460 }
1461 }
1462 }
1463
Glenn Kasten74a8e252014-07-24 14:09:55 -07001464 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001465 if (activeInputsCount() == 0) {
1466 SoundTrigger::setCaptureState(true);
1467 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001468 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001469
Glenn Kasten74a8e252014-07-24 14:09:55 -07001470 // Automatically enable the remote submix output when input is started.
1471 // For remote submix (a virtual device), we open only one input per capture request.
1472 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1473 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1474 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1475 }
Eric Laurente552edb2014-03-10 17:42:56 -07001476 }
1477
Eric Laurente552edb2014-03-10 17:42:56 -07001478 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1479
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001480 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001481 return NO_ERROR;
1482}
1483
Eric Laurent4dc68062014-07-28 17:26:49 -07001484status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1485 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001486{
1487 ALOGV("stopInput() input %d", input);
1488 ssize_t index = mInputs.indexOfKey(input);
1489 if (index < 0) {
1490 ALOGW("stopInput() unknown input %d", input);
1491 return BAD_VALUE;
1492 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001493 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001494
Eric Laurent4dc68062014-07-28 17:26:49 -07001495 index = inputDesc->mSessions.indexOf(session);
1496 if (index < 0) {
1497 ALOGW("stopInput() unknown session %d on input %d", session, input);
1498 return BAD_VALUE;
1499 }
1500
Eric Laurente552edb2014-03-10 17:42:56 -07001501 if (inputDesc->mRefCount == 0) {
1502 ALOGW("stopInput() input %d already stopped", input);
1503 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001504 }
1505
1506 inputDesc->mRefCount--;
1507 if (inputDesc->mRefCount == 0) {
1508
Eric Laurente552edb2014-03-10 17:42:56 -07001509 // automatically disable the remote submix output when input is stopped
1510 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1511 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001512 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001513 }
1514
Eric Laurent1c333e22014-05-20 10:48:17 -07001515 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001516
1517 if (activeInputsCount() == 0) {
1518 SoundTrigger::setCaptureState(false);
1519 }
Eric Laurente552edb2014-03-10 17:42:56 -07001520 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001521 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001522}
1523
Eric Laurent4dc68062014-07-28 17:26:49 -07001524void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1525 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001526{
1527 ALOGV("releaseInput() %d", input);
1528 ssize_t index = mInputs.indexOfKey(input);
1529 if (index < 0) {
1530 ALOGW("releaseInput() releasing unknown input %d", input);
1531 return;
1532 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001533 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1534 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001535
1536 index = inputDesc->mSessions.indexOf(session);
1537 if (index < 0) {
1538 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1539 return;
1540 }
1541 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001542 if (inputDesc->mOpenRefCount == 0) {
1543 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1544 return;
1545 }
1546 inputDesc->mOpenRefCount--;
1547 if (inputDesc->mOpenRefCount > 0) {
1548 ALOGV("releaseInput() exit > 0");
1549 return;
1550 }
1551
Eric Laurent05b90f82014-08-27 15:32:29 -07001552 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001553 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001554 ALOGV("releaseInput() exit");
1555}
1556
Eric Laurentd4692962014-05-05 18:13:44 -07001557void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001558 bool patchRemoved = false;
1559
Eric Laurentd4692962014-05-05 18:13:44 -07001560 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001561 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1562 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1563 if (patch_index >= 0) {
1564 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1565 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1566 mAudioPatches.removeItemsAt(patch_index);
1567 patchRemoved = true;
1568 }
Eric Laurentd4692962014-05-05 18:13:44 -07001569 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1570 }
1571 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001572 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001573
1574 if (patchRemoved) {
1575 mpClientInterface->onAudioPatchListUpdate();
1576 }
Eric Laurentd4692962014-05-05 18:13:44 -07001577}
1578
Eric Laurente0720872014-03-11 09:30:41 -07001579void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001580 int indexMin,
1581 int indexMax)
1582{
1583 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1584 if (indexMin < 0 || indexMin >= indexMax) {
1585 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1586 return;
1587 }
1588 mStreams[stream].mIndexMin = indexMin;
1589 mStreams[stream].mIndexMax = indexMax;
1590}
1591
Eric Laurente0720872014-03-11 09:30:41 -07001592status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001593 int index,
1594 audio_devices_t device)
1595{
1596
1597 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1598 return BAD_VALUE;
1599 }
1600 if (!audio_is_output_device(device)) {
1601 return BAD_VALUE;
1602 }
1603
1604 // Force max volume if stream cannot be muted
1605 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1606
1607 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1608 stream, device, index);
1609
1610 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1611 // clear all device specific values
1612 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1613 mStreams[stream].mIndexCur.clear();
1614 }
1615 mStreams[stream].mIndexCur.add(device, index);
1616
Eric Laurent31551f82014-10-10 18:21:56 -07001617 // update volume on all outputs whose current device is also selected by the same
1618 // strategy as the device specified by the caller
1619 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1620 if ((device != AUDIO_DEVICE_OUT_DEFAULT) && (device & strategyDevice) == 0) {
1621 return NO_ERROR;
1622 }
Eric Laurente552edb2014-03-10 17:42:56 -07001623 status_t status = NO_ERROR;
1624 for (size_t i = 0; i < mOutputs.size(); i++) {
1625 audio_devices_t curDevice =
1626 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001627 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001628 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1629 if (volStatus != NO_ERROR) {
1630 status = volStatus;
1631 }
1632 }
1633 }
1634 return status;
1635}
1636
Eric Laurente0720872014-03-11 09:30:41 -07001637status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001638 int *index,
1639 audio_devices_t device)
1640{
1641 if (index == NULL) {
1642 return BAD_VALUE;
1643 }
1644 if (!audio_is_output_device(device)) {
1645 return BAD_VALUE;
1646 }
1647 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1648 // the strategy the stream belongs to.
1649 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1650 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1651 }
1652 device = getDeviceForVolume(device);
1653
1654 *index = mStreams[stream].getVolumeIndex(device);
1655 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1656 return NO_ERROR;
1657}
1658
Eric Laurente0720872014-03-11 09:30:41 -07001659audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001660 const SortedVector<audio_io_handle_t>& outputs)
1661{
1662 // select one output among several suitable for global effects.
1663 // The priority is as follows:
1664 // 1: An offloaded output. If the effect ends up not being offloadable,
1665 // AudioFlinger will invalidate the track and the offloaded output
1666 // will be closed causing the effect to be moved to a PCM output.
1667 // 2: A deep buffer output
1668 // 3: the first output in the list
1669
1670 if (outputs.size() == 0) {
1671 return 0;
1672 }
1673
1674 audio_io_handle_t outputOffloaded = 0;
1675 audio_io_handle_t outputDeepBuffer = 0;
1676
1677 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001678 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001679 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001680 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1681 outputOffloaded = outputs[i];
1682 }
1683 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1684 outputDeepBuffer = outputs[i];
1685 }
1686 }
1687
1688 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1689 outputOffloaded, outputDeepBuffer);
1690 if (outputOffloaded != 0) {
1691 return outputOffloaded;
1692 }
1693 if (outputDeepBuffer != 0) {
1694 return outputDeepBuffer;
1695 }
1696
1697 return outputs[0];
1698}
1699
Eric Laurente0720872014-03-11 09:30:41 -07001700audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001701{
1702 // apply simple rule where global effects are attached to the same output as MUSIC streams
1703
Eric Laurent3b73df72014-03-11 09:06:29 -07001704 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001705 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1706 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1707
1708 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1709 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1710 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1711
1712 return output;
1713}
1714
Eric Laurente0720872014-03-11 09:30:41 -07001715status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001716 audio_io_handle_t io,
1717 uint32_t strategy,
1718 int session,
1719 int id)
1720{
1721 ssize_t index = mOutputs.indexOfKey(io);
1722 if (index < 0) {
1723 index = mInputs.indexOfKey(io);
1724 if (index < 0) {
1725 ALOGW("registerEffect() unknown io %d", io);
1726 return INVALID_OPERATION;
1727 }
1728 }
1729
1730 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1731 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1732 desc->name, desc->memoryUsage);
1733 return INVALID_OPERATION;
1734 }
1735 mTotalEffectsMemory += desc->memoryUsage;
1736 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1737 desc->name, io, strategy, session, id);
1738 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1739
Eric Laurent1f2f2232014-06-02 12:01:23 -07001740 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1741 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1742 effectDesc->mIo = io;
1743 effectDesc->mStrategy = (routing_strategy)strategy;
1744 effectDesc->mSession = session;
1745 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001746
Eric Laurent1f2f2232014-06-02 12:01:23 -07001747 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001748
1749 return NO_ERROR;
1750}
1751
Eric Laurente0720872014-03-11 09:30:41 -07001752status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001753{
1754 ssize_t index = mEffects.indexOfKey(id);
1755 if (index < 0) {
1756 ALOGW("unregisterEffect() unknown effect ID %d", id);
1757 return INVALID_OPERATION;
1758 }
1759
Eric Laurent1f2f2232014-06-02 12:01:23 -07001760 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001761
Eric Laurent1f2f2232014-06-02 12:01:23 -07001762 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001763
Eric Laurent1f2f2232014-06-02 12:01:23 -07001764 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001765 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001766 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1767 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001768 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001769 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001770 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001771 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001772
1773 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001774
1775 return NO_ERROR;
1776}
1777
Eric Laurente0720872014-03-11 09:30:41 -07001778status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001779{
1780 ssize_t index = mEffects.indexOfKey(id);
1781 if (index < 0) {
1782 ALOGW("unregisterEffect() unknown effect ID %d", id);
1783 return INVALID_OPERATION;
1784 }
1785
1786 return setEffectEnabled(mEffects.valueAt(index), enabled);
1787}
1788
Eric Laurent1f2f2232014-06-02 12:01:23 -07001789status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001790{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001791 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001792 ALOGV("setEffectEnabled(%s) effect already %s",
1793 enabled?"true":"false", enabled?"enabled":"disabled");
1794 return INVALID_OPERATION;
1795 }
1796
1797 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001798 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001799 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001800 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001801 return INVALID_OPERATION;
1802 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001803 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001804 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1805 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001806 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001807 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001808 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1809 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001810 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001811 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001812 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1813 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001814 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001815 return NO_ERROR;
1816}
1817
Eric Laurente0720872014-03-11 09:30:41 -07001818bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001819{
1820 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001821 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1822 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1823 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001824 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001825 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001826 return true;
1827 }
1828 }
1829 return false;
1830}
1831
Eric Laurente0720872014-03-11 09:30:41 -07001832bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001833{
1834 nsecs_t sysTime = systemTime();
1835 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001836 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001837 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001838 return true;
1839 }
1840 }
1841 return false;
1842}
1843
Eric Laurente0720872014-03-11 09:30:41 -07001844bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001845 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001846{
1847 nsecs_t sysTime = systemTime();
1848 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001849 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001850 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001851 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001852 return true;
1853 }
1854 }
1855 return false;
1856}
1857
Eric Laurente0720872014-03-11 09:30:41 -07001858bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001859{
1860 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001861 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001862 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001863 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001864 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1865 && (inputDescriptor->mRefCount > 0)) {
1866 return true;
1867 }
1868 }
1869 return false;
1870}
1871
1872
Eric Laurente0720872014-03-11 09:30:41 -07001873status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001874{
1875 const size_t SIZE = 256;
1876 char buffer[SIZE];
1877 String8 result;
1878
1879 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1880 result.append(buffer);
1881
1882 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1883 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001884 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1885 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001886 snprintf(buffer, SIZE, " Force use for communications %d\n",
1887 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001888 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001889 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001890 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001891 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001892 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001893 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001894 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001895 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001896 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001897 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1898 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1899 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001900
Eric Laurent3a4311c2014-03-17 12:00:47 -07001901 snprintf(buffer, SIZE, " Available output devices:\n");
1902 result.append(buffer);
1903 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001904 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001905 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001906 }
1907 snprintf(buffer, SIZE, "\n Available input devices:\n");
1908 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001909 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001910 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001911 }
Eric Laurente552edb2014-03-10 17:42:56 -07001912
1913 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1914 write(fd, buffer, strlen(buffer));
1915 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001916 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001917 write(fd, buffer, strlen(buffer));
1918 mHwModules[i]->dump(fd);
1919 }
1920
1921 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1922 write(fd, buffer, strlen(buffer));
1923 for (size_t i = 0; i < mOutputs.size(); i++) {
1924 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1925 write(fd, buffer, strlen(buffer));
1926 mOutputs.valueAt(i)->dump(fd);
1927 }
1928
1929 snprintf(buffer, SIZE, "\nInputs dump:\n");
1930 write(fd, buffer, strlen(buffer));
1931 for (size_t i = 0; i < mInputs.size(); i++) {
1932 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1933 write(fd, buffer, strlen(buffer));
1934 mInputs.valueAt(i)->dump(fd);
1935 }
1936
1937 snprintf(buffer, SIZE, "\nStreams dump:\n");
1938 write(fd, buffer, strlen(buffer));
1939 snprintf(buffer, SIZE,
1940 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1941 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001942 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001943 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001944 write(fd, buffer, strlen(buffer));
1945 mStreams[i].dump(fd);
1946 }
1947
1948 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1949 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1950 write(fd, buffer, strlen(buffer));
1951
1952 snprintf(buffer, SIZE, "Registered effects:\n");
1953 write(fd, buffer, strlen(buffer));
1954 for (size_t i = 0; i < mEffects.size(); i++) {
1955 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1956 write(fd, buffer, strlen(buffer));
1957 mEffects.valueAt(i)->dump(fd);
1958 }
1959
Eric Laurent4d416952014-08-10 14:07:09 -07001960 snprintf(buffer, SIZE, "\nAudio Patches:\n");
1961 write(fd, buffer, strlen(buffer));
1962 for (size_t i = 0; i < mAudioPatches.size(); i++) {
1963 mAudioPatches[i]->dump(fd, 2, i);
1964 }
Eric Laurente552edb2014-03-10 17:42:56 -07001965
1966 return NO_ERROR;
1967}
1968
1969// This function checks for the parameters which can be offloaded.
1970// This can be enhanced depending on the capability of the DSP and policy
1971// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001972bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001973{
1974 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001975 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001976 offloadInfo.sample_rate, offloadInfo.channel_mask,
1977 offloadInfo.format,
1978 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1979 offloadInfo.has_video);
1980
1981 // Check if offload has been disabled
1982 char propValue[PROPERTY_VALUE_MAX];
1983 if (property_get("audio.offload.disable", propValue, "0")) {
1984 if (atoi(propValue) != 0) {
1985 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1986 return false;
1987 }
1988 }
1989
1990 // Check if stream type is music, then only allow offload as of now.
1991 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1992 {
1993 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1994 return false;
1995 }
1996
1997 //TODO: enable audio offloading with video when ready
1998 if (offloadInfo.has_video)
1999 {
2000 ALOGV("isOffloadSupported: has_video == true, returning false");
2001 return false;
2002 }
2003
2004 //If duration is less than minimum value defined in property, return false
2005 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2006 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2007 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2008 return false;
2009 }
2010 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2011 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2012 return false;
2013 }
2014
2015 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2016 // creating an offloaded track and tearing it down immediately after start when audioflinger
2017 // detects there is an active non offloadable effect.
2018 // FIXME: We should check the audio session here but we do not have it in this context.
2019 // This may prevent offloading in rare situations where effects are left active by apps
2020 // in the background.
2021 if (isNonOffloadableEffectEnabled()) {
2022 return false;
2023 }
2024
2025 // See if there is a profile to support this.
2026 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002027 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002028 offloadInfo.sample_rate,
2029 offloadInfo.format,
2030 offloadInfo.channel_mask,
2031 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002032 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2033 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002034}
2035
Eric Laurent6a94d692014-05-20 11:18:06 -07002036status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2037 audio_port_type_t type,
2038 unsigned int *num_ports,
2039 struct audio_port *ports,
2040 unsigned int *generation)
2041{
2042 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2043 generation == NULL) {
2044 return BAD_VALUE;
2045 }
2046 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2047 if (ports == NULL) {
2048 *num_ports = 0;
2049 }
2050
2051 size_t portsWritten = 0;
2052 size_t portsMax = *num_ports;
2053 *num_ports = 0;
2054 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2055 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2056 for (size_t i = 0;
2057 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2058 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2059 }
2060 *num_ports += mAvailableOutputDevices.size();
2061 }
2062 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2063 for (size_t i = 0;
2064 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2065 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2066 }
2067 *num_ports += mAvailableInputDevices.size();
2068 }
2069 }
2070 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2071 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2072 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2073 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2074 }
2075 *num_ports += mInputs.size();
2076 }
2077 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002078 size_t numOutputs = 0;
2079 for (size_t i = 0; i < mOutputs.size(); i++) {
2080 if (!mOutputs[i]->isDuplicated()) {
2081 numOutputs++;
2082 if (portsWritten < portsMax) {
2083 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2084 }
2085 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002086 }
Eric Laurent84c70242014-06-23 08:46:27 -07002087 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002088 }
2089 }
2090 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002091 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002092 return NO_ERROR;
2093}
2094
2095status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2096{
2097 return NO_ERROR;
2098}
2099
Eric Laurent1f2f2232014-06-02 12:01:23 -07002100sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002101 audio_port_handle_t id) const
2102{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002103 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002104 for (size_t i = 0; i < mOutputs.size(); i++) {
2105 outputDesc = mOutputs.valueAt(i);
2106 if (outputDesc->mId == id) {
2107 break;
2108 }
2109 }
2110 return outputDesc;
2111}
2112
Eric Laurent1f2f2232014-06-02 12:01:23 -07002113sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002114 audio_port_handle_t id) const
2115{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002116 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002117 for (size_t i = 0; i < mInputs.size(); i++) {
2118 inputDesc = mInputs.valueAt(i);
2119 if (inputDesc->mId == id) {
2120 break;
2121 }
2122 }
2123 return inputDesc;
2124}
2125
Eric Laurent1f2f2232014-06-02 12:01:23 -07002126sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2127 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002128{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002129 sp <HwModule> module;
2130
Eric Laurent6a94d692014-05-20 11:18:06 -07002131 for (size_t i = 0; i < mHwModules.size(); i++) {
2132 if (mHwModules[i]->mHandle == 0) {
2133 continue;
2134 }
2135 if (audio_is_output_device(device)) {
2136 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2137 {
2138 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2139 return mHwModules[i];
2140 }
2141 }
2142 } else {
2143 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2144 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2145 device & ~AUDIO_DEVICE_BIT_IN) {
2146 return mHwModules[i];
2147 }
2148 }
2149 }
2150 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002151 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002152}
2153
Eric Laurent1f2f2232014-06-02 12:01:23 -07002154sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002155{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002156 sp <HwModule> module;
2157
Eric Laurent1afeecb2014-05-14 08:52:28 -07002158 for (size_t i = 0; i < mHwModules.size(); i++)
2159 {
2160 if (strcmp(mHwModules[i]->mName, name) == 0) {
2161 return mHwModules[i];
2162 }
2163 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002164 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002165}
2166
Eric Laurentc2730ba2014-07-20 15:47:07 -07002167audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2168{
2169 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2170 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2171 return devices & mAvailableOutputDevices.types();
2172}
2173
2174audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2175{
2176 audio_module_handle_t primaryHandle =
2177 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2178 audio_devices_t devices = AUDIO_DEVICE_NONE;
2179 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2180 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2181 devices |= mAvailableInputDevices[i]->mDeviceType;
2182 }
2183 }
2184 return devices;
2185}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002186
Eric Laurent6a94d692014-05-20 11:18:06 -07002187status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2188 audio_patch_handle_t *handle,
2189 uid_t uid)
2190{
2191 ALOGV("createAudioPatch()");
2192
2193 if (handle == NULL || patch == NULL) {
2194 return BAD_VALUE;
2195 }
2196 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2197
Eric Laurent874c42872014-08-08 15:13:39 -07002198 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2199 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2200 return BAD_VALUE;
2201 }
2202 // only one source per audio patch supported for now
2203 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002204 return INVALID_OPERATION;
2205 }
Eric Laurent874c42872014-08-08 15:13:39 -07002206
2207 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002208 return INVALID_OPERATION;
2209 }
Eric Laurent874c42872014-08-08 15:13:39 -07002210 for (size_t i = 0; i < patch->num_sinks; i++) {
2211 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2212 return INVALID_OPERATION;
2213 }
2214 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002215
2216 sp<AudioPatch> patchDesc;
2217 ssize_t index = mAudioPatches.indexOfKey(*handle);
2218
Eric Laurent6a94d692014-05-20 11:18:06 -07002219 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2220 patch->sources[0].role,
2221 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002222#if LOG_NDEBUG == 0
2223 for (size_t i = 0; i < patch->num_sinks; i++) {
2224 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2225 patch->sinks[i].role,
2226 patch->sinks[i].type);
2227 }
2228#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002229
2230 if (index >= 0) {
2231 patchDesc = mAudioPatches.valueAt(index);
2232 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2233 mUidCached, patchDesc->mUid, uid);
2234 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2235 return INVALID_OPERATION;
2236 }
2237 } else {
2238 *handle = 0;
2239 }
2240
2241 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002242 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002243 if (outputDesc == NULL) {
2244 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2245 return BAD_VALUE;
2246 }
Eric Laurent84c70242014-06-23 08:46:27 -07002247 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2248 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002249 if (patchDesc != 0) {
2250 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2251 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2252 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2253 return BAD_VALUE;
2254 }
2255 }
Eric Laurent874c42872014-08-08 15:13:39 -07002256 DeviceVector devices;
2257 for (size_t i = 0; i < patch->num_sinks; i++) {
2258 // Only support mix to devices connection
2259 // TODO add support for mix to mix connection
2260 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2261 ALOGV("createAudioPatch() source mix but sink is not a device");
2262 return INVALID_OPERATION;
2263 }
2264 sp<DeviceDescriptor> devDesc =
2265 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2266 if (devDesc == 0) {
2267 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2268 return BAD_VALUE;
2269 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002270
Eric Laurent874c42872014-08-08 15:13:39 -07002271 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2272 patch->sources[0].sample_rate,
2273 NULL, // updatedSamplingRate
2274 patch->sources[0].format,
2275 patch->sources[0].channel_mask,
2276 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2277 ALOGV("createAudioPatch() profile not supported for device %08x",
2278 devDesc->mDeviceType);
2279 return INVALID_OPERATION;
2280 }
2281 devices.add(devDesc);
2282 }
2283 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002284 return INVALID_OPERATION;
2285 }
Eric Laurent874c42872014-08-08 15:13:39 -07002286
Eric Laurent6a94d692014-05-20 11:18:06 -07002287 // TODO: reconfigure output format and channels here
2288 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002289 devices.types(), outputDesc->mIoHandle);
2290 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002291 index = mAudioPatches.indexOfKey(*handle);
2292 if (index >= 0) {
2293 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2294 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2295 }
2296 patchDesc = mAudioPatches.valueAt(index);
2297 patchDesc->mUid = uid;
2298 ALOGV("createAudioPatch() success");
2299 } else {
2300 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2301 return INVALID_OPERATION;
2302 }
2303 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2304 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2305 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002306 // only one sink supported when connecting an input device to a mix
2307 if (patch->num_sinks > 1) {
2308 return INVALID_OPERATION;
2309 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002310 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002311 if (inputDesc == NULL) {
2312 return BAD_VALUE;
2313 }
2314 if (patchDesc != 0) {
2315 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2316 return BAD_VALUE;
2317 }
2318 }
2319 sp<DeviceDescriptor> devDesc =
2320 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2321 if (devDesc == 0) {
2322 return BAD_VALUE;
2323 }
2324
Eric Laurent84c70242014-06-23 08:46:27 -07002325 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002326 patch->sinks[0].sample_rate,
2327 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002328 patch->sinks[0].format,
2329 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002330 // FIXME for the parameter type,
2331 // and the NONE
2332 (audio_output_flags_t)
2333 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002334 return INVALID_OPERATION;
2335 }
2336 // TODO: reconfigure output format and channels here
2337 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002338 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002339 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002340 index = mAudioPatches.indexOfKey(*handle);
2341 if (index >= 0) {
2342 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2343 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2344 }
2345 patchDesc = mAudioPatches.valueAt(index);
2346 patchDesc->mUid = uid;
2347 ALOGV("createAudioPatch() success");
2348 } else {
2349 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2350 return INVALID_OPERATION;
2351 }
2352 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2353 // device to device connection
2354 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002355 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002356 return BAD_VALUE;
2357 }
2358 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002359 sp<DeviceDescriptor> srcDeviceDesc =
2360 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002361 if (srcDeviceDesc == 0) {
2362 return BAD_VALUE;
2363 }
Eric Laurent874c42872014-08-08 15:13:39 -07002364
Eric Laurent6a94d692014-05-20 11:18:06 -07002365 //update source and sink with our own data as the data passed in the patch may
2366 // be incomplete.
2367 struct audio_patch newPatch = *patch;
2368 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002369
Eric Laurent874c42872014-08-08 15:13:39 -07002370 for (size_t i = 0; i < patch->num_sinks; i++) {
2371 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2372 ALOGV("createAudioPatch() source device but one sink is not a device");
2373 return INVALID_OPERATION;
2374 }
2375
2376 sp<DeviceDescriptor> sinkDeviceDesc =
2377 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2378 if (sinkDeviceDesc == 0) {
2379 return BAD_VALUE;
2380 }
2381 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2382
2383 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2384 // only one sink supported when connected devices across HW modules
2385 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002386 return INVALID_OPERATION;
2387 }
Eric Laurent874c42872014-08-08 15:13:39 -07002388 SortedVector<audio_io_handle_t> outputs =
2389 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2390 mOutputs);
2391 // if the sink device is reachable via an opened output stream, request to go via
2392 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002393 audio_io_handle_t output = selectOutput(outputs,
2394 AUDIO_OUTPUT_FLAG_NONE,
2395 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002396 if (output != AUDIO_IO_HANDLE_NONE) {
2397 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2398 if (outputDesc->isDuplicated()) {
2399 return INVALID_OPERATION;
2400 }
2401 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2402 newPatch.num_sources = 2;
2403 }
Eric Laurent83b88082014-06-20 18:31:16 -07002404 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002405 }
2406 // TODO: check from routing capabilities in config file and other conflicting patches
2407
2408 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2409 if (index >= 0) {
2410 afPatchHandle = patchDesc->mAfPatchHandle;
2411 }
2412
2413 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2414 &afPatchHandle,
2415 0);
2416 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2417 status, afPatchHandle);
2418 if (status == NO_ERROR) {
2419 if (index < 0) {
2420 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2421 &newPatch, uid);
2422 addAudioPatch(patchDesc->mHandle, patchDesc);
2423 } else {
2424 patchDesc->mPatch = newPatch;
2425 }
2426 patchDesc->mAfPatchHandle = afPatchHandle;
2427 *handle = patchDesc->mHandle;
2428 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002429 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002430 } else {
2431 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2432 status);
2433 return INVALID_OPERATION;
2434 }
2435 } else {
2436 return BAD_VALUE;
2437 }
2438 } else {
2439 return BAD_VALUE;
2440 }
2441 return NO_ERROR;
2442}
2443
2444status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2445 uid_t uid)
2446{
2447 ALOGV("releaseAudioPatch() patch %d", handle);
2448
2449 ssize_t index = mAudioPatches.indexOfKey(handle);
2450
2451 if (index < 0) {
2452 return BAD_VALUE;
2453 }
2454 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2455 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2456 mUidCached, patchDesc->mUid, uid);
2457 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2458 return INVALID_OPERATION;
2459 }
2460
2461 struct audio_patch *patch = &patchDesc->mPatch;
2462 patchDesc->mUid = mUidCached;
2463 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002464 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002465 if (outputDesc == NULL) {
2466 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2467 return BAD_VALUE;
2468 }
2469
2470 setOutputDevice(outputDesc->mIoHandle,
2471 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2472 true,
2473 0,
2474 NULL);
2475 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2476 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002477 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002478 if (inputDesc == NULL) {
2479 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2480 return BAD_VALUE;
2481 }
2482 setInputDevice(inputDesc->mIoHandle,
2483 getNewInputDevice(inputDesc->mIoHandle),
2484 true,
2485 NULL);
2486 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2487 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2488 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2489 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2490 status, patchDesc->mAfPatchHandle);
2491 removeAudioPatch(patchDesc->mHandle);
2492 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002493 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002494 } else {
2495 return BAD_VALUE;
2496 }
2497 } else {
2498 return BAD_VALUE;
2499 }
2500 return NO_ERROR;
2501}
2502
2503status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2504 struct audio_patch *patches,
2505 unsigned int *generation)
2506{
2507 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2508 generation == NULL) {
2509 return BAD_VALUE;
2510 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002511 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002512 *num_patches, patches, mAudioPatches.size());
2513 if (patches == NULL) {
2514 *num_patches = 0;
2515 }
2516
2517 size_t patchesWritten = 0;
2518 size_t patchesMax = *num_patches;
2519 for (size_t i = 0;
2520 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2521 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2522 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002523 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002524 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2525 }
2526 *num_patches = mAudioPatches.size();
2527
2528 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002529 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002530 return NO_ERROR;
2531}
2532
Eric Laurente1715a42014-05-20 11:30:42 -07002533status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002534{
Eric Laurente1715a42014-05-20 11:30:42 -07002535 ALOGV("setAudioPortConfig()");
2536
2537 if (config == NULL) {
2538 return BAD_VALUE;
2539 }
2540 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2541 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002542 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2543 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002544 }
2545
Eric Laurenta121f902014-06-03 13:32:54 -07002546 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002547 if (config->type == AUDIO_PORT_TYPE_MIX) {
2548 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002549 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002550 if (outputDesc == NULL) {
2551 return BAD_VALUE;
2552 }
Eric Laurent84c70242014-06-23 08:46:27 -07002553 ALOG_ASSERT(!outputDesc->isDuplicated(),
2554 "setAudioPortConfig() called on duplicated output %d",
2555 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002556 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002557 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002558 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002559 if (inputDesc == NULL) {
2560 return BAD_VALUE;
2561 }
Eric Laurenta121f902014-06-03 13:32:54 -07002562 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002563 } else {
2564 return BAD_VALUE;
2565 }
2566 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2567 sp<DeviceDescriptor> deviceDesc;
2568 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2569 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2570 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2571 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2572 } else {
2573 return BAD_VALUE;
2574 }
2575 if (deviceDesc == NULL) {
2576 return BAD_VALUE;
2577 }
Eric Laurenta121f902014-06-03 13:32:54 -07002578 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002579 } else {
2580 return BAD_VALUE;
2581 }
2582
Eric Laurenta121f902014-06-03 13:32:54 -07002583 struct audio_port_config backupConfig;
2584 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2585 if (status == NO_ERROR) {
2586 struct audio_port_config newConfig;
2587 audioPortConfig->toAudioPortConfig(&newConfig, config);
2588 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002589 }
Eric Laurenta121f902014-06-03 13:32:54 -07002590 if (status != NO_ERROR) {
2591 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002592 }
Eric Laurente1715a42014-05-20 11:30:42 -07002593
2594 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002595}
2596
2597void AudioPolicyManager::clearAudioPatches(uid_t uid)
2598{
2599 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2600 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2601 if (patchDesc->mUid == uid) {
2602 // releaseAudioPatch() removes the patch from mAudioPatches
2603 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2604 i--;
2605 }
2606 }
2607 }
2608}
2609
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002610status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2611 audio_io_handle_t *ioHandle,
2612 audio_devices_t *device)
2613{
2614 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2615 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2616 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2617
2618 mSoundTriggerSessions.add(*session, *ioHandle);
2619
2620 return NO_ERROR;
2621}
2622
2623status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2624{
2625 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2626 if (index < 0) {
2627 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2628 return BAD_VALUE;
2629 }
2630
2631 mSoundTriggerSessions.removeItem(session);
2632 return NO_ERROR;
2633}
2634
Eric Laurent6a94d692014-05-20 11:18:06 -07002635status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2636 const sp<AudioPatch>& patch)
2637{
2638 ssize_t index = mAudioPatches.indexOfKey(handle);
2639
2640 if (index >= 0) {
2641 ALOGW("addAudioPatch() patch %d already in", handle);
2642 return ALREADY_EXISTS;
2643 }
2644 mAudioPatches.add(handle, patch);
2645 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2646 "sink handle %d",
2647 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2648 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2649 return NO_ERROR;
2650}
2651
2652status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2653{
2654 ssize_t index = mAudioPatches.indexOfKey(handle);
2655
2656 if (index < 0) {
2657 ALOGW("removeAudioPatch() patch %d not in", handle);
2658 return ALREADY_EXISTS;
2659 }
2660 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2661 mAudioPatches.valueAt(index)->mAfPatchHandle);
2662 mAudioPatches.removeItemsAt(index);
2663 return NO_ERROR;
2664}
2665
Eric Laurente552edb2014-03-10 17:42:56 -07002666// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002667// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002668// ----------------------------------------------------------------------------
2669
Eric Laurent3a4311c2014-03-17 12:00:47 -07002670uint32_t AudioPolicyManager::nextUniqueId()
2671{
2672 return android_atomic_inc(&mNextUniqueId);
2673}
2674
Eric Laurent6a94d692014-05-20 11:18:06 -07002675uint32_t AudioPolicyManager::nextAudioPortGeneration()
2676{
2677 return android_atomic_inc(&mAudioPortGeneration);
2678}
2679
Eric Laurente0720872014-03-11 09:30:41 -07002680AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002681 :
2682#ifdef AUDIO_POLICY_TEST
2683 Thread(false),
2684#endif //AUDIO_POLICY_TEST
2685 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002686 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002687 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2688 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002689 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002690 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002691 mAudioPortGeneration(1),
2692 mBeaconMuteRefCount(0),
2693 mBeaconPlayingRefCount(0),
2694 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07002695{
Eric Laurent6a94d692014-05-20 11:18:06 -07002696 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002697 mpClientInterface = clientInterface;
2698
Eric Laurent3b73df72014-03-11 09:06:29 -07002699 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2700 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002701 }
2702
Eric Laurent1afeecb2014-05-14 08:52:28 -07002703 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002704 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2705 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2706 ALOGE("could not load audio policy configuration file, setting defaults");
2707 defaultAudioPolicyConfig();
2708 }
2709 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002710 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002711
2712 // must be done after reading the policy
2713 initializeVolumeCurves();
2714
2715 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002716 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2717 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002718 for (size_t i = 0; i < mHwModules.size(); i++) {
2719 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2720 if (mHwModules[i]->mHandle == 0) {
2721 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2722 continue;
2723 }
2724 // open all output streams needed to access attached devices
2725 // except for direct output streams that are only opened when they are actually
2726 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002727 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002728 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2729 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002730 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002731
Eric Laurent3a4311c2014-03-17 12:00:47 -07002732 if (outProfile->mSupportedDevices.isEmpty()) {
2733 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2734 continue;
2735 }
2736
Eric Laurentd78f1532014-09-16 16:38:20 -07002737 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
2738 continue;
2739 }
Eric Laurent83b88082014-06-20 18:31:16 -07002740 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2741 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2742 profileType = mDefaultOutputDevice->mDeviceType;
2743 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07002744 // chose first device present in mSupportedDevices also part of
2745 // outputDeviceTypes
2746 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2747 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
2748 if ((profileType & outputDeviceTypes) != 0) {
2749 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002750 }
Eric Laurente552edb2014-03-10 17:42:56 -07002751 }
2752 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002753 if ((profileType & outputDeviceTypes) == 0) {
2754 continue;
2755 }
2756 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
2757
2758 outputDesc->mDevice = profileType;
2759 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2760 config.sample_rate = outputDesc->mSamplingRate;
2761 config.channel_mask = outputDesc->mChannelMask;
2762 config.format = outputDesc->mFormat;
2763 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2764 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2765 &output,
2766 &config,
2767 &outputDesc->mDevice,
2768 String8(""),
2769 &outputDesc->mLatency,
2770 outputDesc->mFlags);
2771
2772 if (status != NO_ERROR) {
2773 ALOGW("Cannot open output stream for device %08x on hw module %s",
2774 outputDesc->mDevice,
2775 mHwModules[i]->mName);
2776 } else {
2777 outputDesc->mSamplingRate = config.sample_rate;
2778 outputDesc->mChannelMask = config.channel_mask;
2779 outputDesc->mFormat = config.format;
2780
2781 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2782 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
2783 ssize_t index =
2784 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2785 // give a valid ID to an attached device once confirmed it is reachable
2786 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2787 mAvailableOutputDevices[index]->mId = nextUniqueId();
2788 mAvailableOutputDevices[index]->mModule = mHwModules[i];
2789 }
2790 }
2791 if (mPrimaryOutput == 0 &&
2792 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2793 mPrimaryOutput = output;
2794 }
2795 addOutput(output, outputDesc);
2796 setOutputDevice(output,
2797 outputDesc->mDevice,
2798 true);
2799 }
Eric Laurente552edb2014-03-10 17:42:56 -07002800 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002801 // open input streams needed to access attached devices to validate
2802 // mAvailableInputDevices list
2803 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2804 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002805 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002806
Eric Laurent3a4311c2014-03-17 12:00:47 -07002807 if (inProfile->mSupportedDevices.isEmpty()) {
2808 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2809 continue;
2810 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002811 // chose first device present in mSupportedDevices also part of
2812 // inputDeviceTypes
2813 audio_devices_t profileType = AUDIO_DEVICE_NONE;
2814 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2815 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
2816 if (profileType & inputDeviceTypes) {
2817 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002818 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002819 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002820 if ((profileType & inputDeviceTypes) == 0) {
2821 continue;
2822 }
2823 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2824
2825 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2826 inputDesc->mDevice = profileType;
2827
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002828 // find the address
2829 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
2830 // the inputs vector must be of size 1, but we don't want to crash here
2831 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
2832 : String8("");
2833 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
2834 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
2835
Eric Laurentd78f1532014-09-16 16:38:20 -07002836 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2837 config.sample_rate = inputDesc->mSamplingRate;
2838 config.channel_mask = inputDesc->mChannelMask;
2839 config.format = inputDesc->mFormat;
2840 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2841 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2842 &input,
2843 &config,
2844 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002845 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07002846 AUDIO_SOURCE_MIC,
2847 AUDIO_INPUT_FLAG_NONE);
2848
2849 if (status == NO_ERROR) {
2850 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2851 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
2852 ssize_t index =
2853 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2854 // give a valid ID to an attached device once confirmed it is reachable
2855 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2856 mAvailableInputDevices[index]->mId = nextUniqueId();
2857 mAvailableInputDevices[index]->mModule = mHwModules[i];
2858 }
2859 }
2860 mpClientInterface->closeInput(input);
2861 } else {
2862 ALOGW("Cannot open input stream for device %08x on hw module %s",
2863 inputDesc->mDevice,
2864 mHwModules[i]->mName);
2865 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002866 }
2867 }
2868 // make sure all attached devices have been allocated a unique ID
2869 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2870 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002871 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002872 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2873 continue;
2874 }
2875 i++;
2876 }
2877 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2878 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002879 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002880 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2881 continue;
2882 }
2883 i++;
2884 }
2885 // make sure default device is reachable
2886 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002887 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002888 }
Eric Laurente552edb2014-03-10 17:42:56 -07002889
2890 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2891
2892 updateDevicesAndOutputs();
2893
2894#ifdef AUDIO_POLICY_TEST
2895 if (mPrimaryOutput != 0) {
2896 AudioParameter outputCmd = AudioParameter();
2897 outputCmd.addInt(String8("set_id"), 0);
2898 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2899
2900 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2901 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002902 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2903 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002904 mTestLatencyMs = 0;
2905 mCurOutput = 0;
2906 mDirectOutput = false;
2907 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2908 mTestOutputs[i] = 0;
2909 }
2910
2911 const size_t SIZE = 256;
2912 char buffer[SIZE];
2913 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2914 run(buffer, ANDROID_PRIORITY_AUDIO);
2915 }
2916#endif //AUDIO_POLICY_TEST
2917}
2918
Eric Laurente0720872014-03-11 09:30:41 -07002919AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002920{
2921#ifdef AUDIO_POLICY_TEST
2922 exit();
2923#endif //AUDIO_POLICY_TEST
2924 for (size_t i = 0; i < mOutputs.size(); i++) {
2925 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002926 }
2927 for (size_t i = 0; i < mInputs.size(); i++) {
2928 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002929 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002930 mAvailableOutputDevices.clear();
2931 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002932 mOutputs.clear();
2933 mInputs.clear();
2934 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002935}
2936
Eric Laurente0720872014-03-11 09:30:41 -07002937status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002938{
2939 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2940}
2941
2942#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002943bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002944{
2945 ALOGV("entering threadLoop()");
2946 while (!exitPending())
2947 {
2948 String8 command;
2949 int valueInt;
2950 String8 value;
2951
2952 Mutex::Autolock _l(mLock);
2953 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2954
2955 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2956 AudioParameter param = AudioParameter(command);
2957
2958 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2959 valueInt != 0) {
2960 ALOGV("Test command %s received", command.string());
2961 String8 target;
2962 if (param.get(String8("target"), target) != NO_ERROR) {
2963 target = "Manager";
2964 }
2965 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2966 param.remove(String8("test_cmd_policy_output"));
2967 mCurOutput = valueInt;
2968 }
2969 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2970 param.remove(String8("test_cmd_policy_direct"));
2971 if (value == "false") {
2972 mDirectOutput = false;
2973 } else if (value == "true") {
2974 mDirectOutput = true;
2975 }
2976 }
2977 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2978 param.remove(String8("test_cmd_policy_input"));
2979 mTestInput = valueInt;
2980 }
2981
2982 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2983 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002984 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002985 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002986 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002987 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002988 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002989 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002990 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002991 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002992 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002993 if (target == "Manager") {
2994 mTestFormat = format;
2995 } else if (mTestOutputs[mCurOutput] != 0) {
2996 AudioParameter outputParam = AudioParameter();
2997 outputParam.addInt(String8("format"), format);
2998 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2999 }
3000 }
3001 }
3002 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3003 param.remove(String8("test_cmd_policy_channels"));
3004 int channels = 0;
3005
3006 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003007 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003008 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003009 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003010 }
3011 if (channels != 0) {
3012 if (target == "Manager") {
3013 mTestChannels = channels;
3014 } else if (mTestOutputs[mCurOutput] != 0) {
3015 AudioParameter outputParam = AudioParameter();
3016 outputParam.addInt(String8("channels"), channels);
3017 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3018 }
3019 }
3020 }
3021 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3022 param.remove(String8("test_cmd_policy_sampleRate"));
3023 if (valueInt >= 0 && valueInt <= 96000) {
3024 int samplingRate = valueInt;
3025 if (target == "Manager") {
3026 mTestSamplingRate = samplingRate;
3027 } else if (mTestOutputs[mCurOutput] != 0) {
3028 AudioParameter outputParam = AudioParameter();
3029 outputParam.addInt(String8("sampling_rate"), samplingRate);
3030 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3031 }
3032 }
3033 }
3034
3035 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3036 param.remove(String8("test_cmd_policy_reopen"));
3037
Eric Laurent1f2f2232014-06-02 12:01:23 -07003038 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003039 mpClientInterface->closeOutput(mPrimaryOutput);
3040
3041 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3042
Eric Laurente552edb2014-03-10 17:42:56 -07003043 mOutputs.removeItem(mPrimaryOutput);
3044
Eric Laurent1f2f2232014-06-02 12:01:23 -07003045 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003046 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003047 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3048 config.sample_rate = outputDesc->mSamplingRate;
3049 config.channel_mask = outputDesc->mChannelMask;
3050 config.format = outputDesc->mFormat;
3051 status_t status = mpClientInterface->openOutput(moduleHandle,
3052 &mPrimaryOutput,
3053 &config,
3054 &outputDesc->mDevice,
3055 String8(""),
3056 &outputDesc->mLatency,
3057 outputDesc->mFlags);
3058 if (status != NO_ERROR) {
3059 ALOGE("Failed to reopen hardware output stream, "
3060 "samplingRate: %d, format %d, channels %d",
3061 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003062 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003063 outputDesc->mSamplingRate = config.sample_rate;
3064 outputDesc->mChannelMask = config.channel_mask;
3065 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003066 AudioParameter outputCmd = AudioParameter();
3067 outputCmd.addInt(String8("set_id"), 0);
3068 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3069 addOutput(mPrimaryOutput, outputDesc);
3070 }
3071 }
3072
3073
3074 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3075 }
3076 }
3077 return false;
3078}
3079
Eric Laurente0720872014-03-11 09:30:41 -07003080void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003081{
3082 {
3083 AutoMutex _l(mLock);
3084 requestExit();
3085 mWaitWorkCV.signal();
3086 }
3087 requestExitAndWait();
3088}
3089
Eric Laurente0720872014-03-11 09:30:41 -07003090int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003091{
3092 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3093 if (output == mTestOutputs[i]) return i;
3094 }
3095 return 0;
3096}
3097#endif //AUDIO_POLICY_TEST
3098
3099// ---
3100
Eric Laurent1f2f2232014-06-02 12:01:23 -07003101void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003102{
Eric Laurent1c333e22014-05-20 10:48:17 -07003103 outputDesc->mIoHandle = output;
3104 outputDesc->mId = nextUniqueId();
3105 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003106 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003107}
3108
Eric Laurent1f2f2232014-06-02 12:01:23 -07003109void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003110{
Eric Laurent1c333e22014-05-20 10:48:17 -07003111 inputDesc->mIoHandle = input;
3112 inputDesc->mId = nextUniqueId();
3113 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003114 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003115}
Eric Laurente552edb2014-03-10 17:42:56 -07003116
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003117void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3118 const String8 address /*in*/,
3119 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3120 // look for a match on the given address on the addresses of the outputs:
3121 // find the address by finding the patch that maps to this output
3122 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3123 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3124 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3125 if (patchIdx >= 0) {
3126 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3127 const int numSinks = patchDesc->mPatch.num_sinks;
3128 for (ssize_t j=0; j < numSinks; j++) {
3129 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3130 const char* patchAddr =
3131 patchDesc->mPatch.sinks[j].ext.device.address;
3132 if (strncmp(patchAddr,
3133 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003134 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003135 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3136 outputs.add(desc->mIoHandle);
3137 break;
3138 }
3139 }
3140 }
3141 }
3142}
3143
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003144status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003145 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003146 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003147 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003148{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003149 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003150 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003151 // erase all current sample rates, formats and channel masks
3152 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003153
Eric Laurent3b73df72014-03-11 09:06:29 -07003154 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003155 // first list already open outputs that can be routed to this device
3156 for (size_t i = 0; i < mOutputs.size(); i++) {
3157 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003158 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003159 if (!deviceDistinguishesOnAddress(device)) {
3160 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3161 outputs.add(mOutputs.keyAt(i));
3162 } else {
3163 ALOGV(" checking address match due to device 0x%x", device);
3164 findIoHandlesByAddress(desc, address, outputs);
3165 }
Eric Laurente552edb2014-03-10 17:42:56 -07003166 }
3167 }
3168 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003169 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003170 for (size_t i = 0; i < mHwModules.size(); i++)
3171 {
3172 if (mHwModules[i]->mHandle == 0) {
3173 continue;
3174 }
3175 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3176 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003177 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003178 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003179 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3180 }
3181 }
3182 }
3183
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003184 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3185
Eric Laurente552edb2014-03-10 17:42:56 -07003186 if (profiles.isEmpty() && outputs.isEmpty()) {
3187 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3188 return BAD_VALUE;
3189 }
3190
3191 // open outputs for matching profiles if needed. Direct outputs are also opened to
3192 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3193 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003194 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003195
3196 // nothing to do if one output is already opened for this profile
3197 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003198 for (j = 0; j < outputs.size(); j++) {
3199 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003200 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003201 // matching profile: save the sample rates, format and channel masks supported
3202 // by the profile in our device descriptor
3203 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003204 break;
3205 }
3206 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003207 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003208 continue;
3209 }
3210
Eric Laurent83b88082014-06-20 18:31:16 -07003211 ALOGV("opening output for device %08x with params %s profile %p",
3212 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003213 desc = new AudioOutputDescriptor(profile);
3214 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003215 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3216 config.sample_rate = desc->mSamplingRate;
3217 config.channel_mask = desc->mChannelMask;
3218 config.format = desc->mFormat;
3219 config.offload_info.sample_rate = desc->mSamplingRate;
3220 config.offload_info.channel_mask = desc->mChannelMask;
3221 config.offload_info.format = desc->mFormat;
3222 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3223 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3224 &output,
3225 &config,
3226 &desc->mDevice,
3227 address,
3228 &desc->mLatency,
3229 desc->mFlags);
3230 if (status == NO_ERROR) {
3231 desc->mSamplingRate = config.sample_rate;
3232 desc->mChannelMask = config.channel_mask;
3233 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003234
Eric Laurentd4692962014-05-05 18:13:44 -07003235 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003236 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003237 char *param = audio_device_address_to_parameter(device, address);
3238 mpClientInterface->setParameters(output, String8(param));
3239 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003240 }
3241
Eric Laurentd4692962014-05-05 18:13:44 -07003242 // Here is where we step through and resolve any "dynamic" fields
3243 String8 reply;
3244 char *value;
3245 if (profile->mSamplingRates[0] == 0) {
3246 reply = mpClientInterface->getParameters(output,
3247 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003248 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003249 reply.string());
3250 value = strpbrk((char *)reply.string(), "=");
3251 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003252 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003253 }
Eric Laurentd4692962014-05-05 18:13:44 -07003254 }
3255 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3256 reply = mpClientInterface->getParameters(output,
3257 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003258 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003259 reply.string());
3260 value = strpbrk((char *)reply.string(), "=");
3261 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003262 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003263 }
Eric Laurentd4692962014-05-05 18:13:44 -07003264 }
3265 if (profile->mChannelMasks[0] == 0) {
3266 reply = mpClientInterface->getParameters(output,
3267 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003268 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003269 reply.string());
3270 value = strpbrk((char *)reply.string(), "=");
3271 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003272 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003273 }
Eric Laurentd4692962014-05-05 18:13:44 -07003274 }
3275 if (((profile->mSamplingRates[0] == 0) &&
3276 (profile->mSamplingRates.size() < 2)) ||
3277 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3278 (profile->mFormats.size() < 2)) ||
3279 ((profile->mChannelMasks[0] == 0) &&
3280 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003281 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003282 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003283 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003284 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3285 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003286 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003287 config.sample_rate = profile->pickSamplingRate();
3288 config.channel_mask = profile->pickChannelMask();
3289 config.format = profile->pickFormat();
3290 config.offload_info.sample_rate = config.sample_rate;
3291 config.offload_info.channel_mask = config.channel_mask;
3292 config.offload_info.format = config.format;
3293 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3294 &output,
3295 &config,
3296 &desc->mDevice,
3297 address,
3298 &desc->mLatency,
3299 desc->mFlags);
3300 if (status == NO_ERROR) {
3301 desc->mSamplingRate = config.sample_rate;
3302 desc->mChannelMask = config.channel_mask;
3303 desc->mFormat = config.format;
3304 } else {
3305 output = AUDIO_IO_HANDLE_NONE;
3306 }
Eric Laurentd4692962014-05-05 18:13:44 -07003307 }
3308
Eric Laurentcf2c0212014-07-25 16:20:43 -07003309 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003310 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003311 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003312 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003313
Eric Laurentd4692962014-05-05 18:13:44 -07003314 // set initial stream volume for device
3315 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003316
Eric Laurentd4692962014-05-05 18:13:44 -07003317 //TODO: configure audio effect output stage here
3318
3319 // open a duplicating output thread for the new output and the primary output
3320 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3321 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003322 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003323 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003324 sp<AudioOutputDescriptor> dupOutputDesc =
3325 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003326 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3327 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3328 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3329 dupOutputDesc->mFormat = desc->mFormat;
3330 dupOutputDesc->mChannelMask = desc->mChannelMask;
3331 dupOutputDesc->mLatency = desc->mLatency;
3332 addOutput(duplicatedOutput, dupOutputDesc);
3333 applyStreamVolumes(duplicatedOutput, device, 0, true);
3334 } else {
3335 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3336 mPrimaryOutput, output);
3337 mpClientInterface->closeOutput(output);
3338 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003339 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003340 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003341 }
Eric Laurente552edb2014-03-10 17:42:56 -07003342 }
3343 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003344 } else {
3345 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003346 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003347 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003348 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003349 profiles.removeAt(profile_index);
3350 profile_index--;
3351 } else {
3352 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003353 devDesc->importAudioPort(profile);
3354
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003355 if (deviceDistinguishesOnAddress(device)) {
3356 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3357 device, address.string());
3358 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3359 NULL/*patch handle*/, address.string());
3360 }
Eric Laurente552edb2014-03-10 17:42:56 -07003361 ALOGV("checkOutputsForDevice(): adding output %d", output);
3362 }
3363 }
3364
3365 if (profiles.isEmpty()) {
3366 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3367 return BAD_VALUE;
3368 }
Eric Laurentd4692962014-05-05 18:13:44 -07003369 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003370 // check if one opened output is not needed any more after disconnecting one device
3371 for (size_t i = 0; i < mOutputs.size(); i++) {
3372 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003373 if (!desc->isDuplicated()) {
3374 if (!(desc->mProfile->mSupportedDevices.types()
3375 & mAvailableOutputDevices.types())) {
3376 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3377 mOutputs.keyAt(i));
3378 outputs.add(mOutputs.keyAt(i));
3379 } else if (deviceDistinguishesOnAddress(device) &&
3380 // exact match on device
3381 (desc->mProfile->mSupportedDevices.types() == device)) {
3382 findIoHandlesByAddress(desc, address, outputs);
3383 }
Eric Laurente552edb2014-03-10 17:42:56 -07003384 }
3385 }
Eric Laurentd4692962014-05-05 18:13:44 -07003386 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003387 for (size_t i = 0; i < mHwModules.size(); i++)
3388 {
3389 if (mHwModules[i]->mHandle == 0) {
3390 continue;
3391 }
3392 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3393 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003394 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003395 if (profile->mSupportedDevices.types() & device) {
3396 ALOGV("checkOutputsForDevice(): "
3397 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003398 if (profile->mSamplingRates[0] == 0) {
3399 profile->mSamplingRates.clear();
3400 profile->mSamplingRates.add(0);
3401 }
3402 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3403 profile->mFormats.clear();
3404 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3405 }
3406 if (profile->mChannelMasks[0] == 0) {
3407 profile->mChannelMasks.clear();
3408 profile->mChannelMasks.add(0);
3409 }
3410 }
3411 }
3412 }
3413 }
3414 return NO_ERROR;
3415}
3416
Eric Laurentd4692962014-05-05 18:13:44 -07003417status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3418 audio_policy_dev_state_t state,
3419 SortedVector<audio_io_handle_t>& inputs,
3420 const String8 address)
3421{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003422 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003423 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3424 // first list already open inputs that can be routed to this device
3425 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3426 desc = mInputs.valueAt(input_index);
3427 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3428 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3429 inputs.add(mInputs.keyAt(input_index));
3430 }
3431 }
3432
3433 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003434 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003435 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3436 {
3437 if (mHwModules[module_idx]->mHandle == 0) {
3438 continue;
3439 }
3440 for (size_t profile_index = 0;
3441 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3442 profile_index++)
3443 {
3444 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3445 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003446 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003447 profile_index, module_idx);
3448 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3449 }
3450 }
3451 }
3452
3453 if (profiles.isEmpty() && inputs.isEmpty()) {
3454 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3455 return BAD_VALUE;
3456 }
3457
3458 // open inputs for matching profiles if needed. Direct inputs are also opened to
3459 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3460 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3461
Eric Laurent1c333e22014-05-20 10:48:17 -07003462 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003463 // nothing to do if one input is already opened for this profile
3464 size_t input_index;
3465 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3466 desc = mInputs.valueAt(input_index);
3467 if (desc->mProfile == profile) {
3468 break;
3469 }
3470 }
3471 if (input_index != mInputs.size()) {
3472 continue;
3473 }
3474
3475 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3476 desc = new AudioInputDescriptor(profile);
3477 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003478 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3479 config.sample_rate = desc->mSamplingRate;
3480 config.channel_mask = desc->mChannelMask;
3481 config.format = desc->mFormat;
3482 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3483 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3484 &input,
3485 &config,
3486 &desc->mDevice,
3487 address,
3488 AUDIO_SOURCE_MIC,
3489 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003490
Eric Laurentcf2c0212014-07-25 16:20:43 -07003491 if (status == NO_ERROR) {
3492 desc->mSamplingRate = config.sample_rate;
3493 desc->mChannelMask = config.channel_mask;
3494 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003495
Eric Laurentd4692962014-05-05 18:13:44 -07003496 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003497 char *param = audio_device_address_to_parameter(device, address);
3498 mpClientInterface->setParameters(input, String8(param));
3499 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003500 }
3501
3502 // Here is where we step through and resolve any "dynamic" fields
3503 String8 reply;
3504 char *value;
3505 if (profile->mSamplingRates[0] == 0) {
3506 reply = mpClientInterface->getParameters(input,
3507 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3508 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3509 reply.string());
3510 value = strpbrk((char *)reply.string(), "=");
3511 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003512 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003513 }
3514 }
3515 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3516 reply = mpClientInterface->getParameters(input,
3517 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3518 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3519 value = strpbrk((char *)reply.string(), "=");
3520 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003521 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003522 }
3523 }
3524 if (profile->mChannelMasks[0] == 0) {
3525 reply = mpClientInterface->getParameters(input,
3526 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3527 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3528 reply.string());
3529 value = strpbrk((char *)reply.string(), "=");
3530 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003531 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003532 }
3533 }
3534 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3535 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3536 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3537 ALOGW("checkInputsForDevice() direct input missing param");
3538 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003539 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003540 }
3541
3542 if (input != 0) {
3543 addInput(input, desc);
3544 }
3545 } // endif input != 0
3546
Eric Laurentcf2c0212014-07-25 16:20:43 -07003547 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003548 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003549 profiles.removeAt(profile_index);
3550 profile_index--;
3551 } else {
3552 inputs.add(input);
3553 ALOGV("checkInputsForDevice(): adding input %d", input);
3554 }
3555 } // end scan profiles
3556
3557 if (profiles.isEmpty()) {
3558 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3559 return BAD_VALUE;
3560 }
3561 } else {
3562 // Disconnect
3563 // check if one opened input is not needed any more after disconnecting one device
3564 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3565 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003566 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3567 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003568 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3569 mInputs.keyAt(input_index));
3570 inputs.add(mInputs.keyAt(input_index));
3571 }
3572 }
3573 // Clear any profiles associated with the disconnected device.
3574 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3575 if (mHwModules[module_index]->mHandle == 0) {
3576 continue;
3577 }
3578 for (size_t profile_index = 0;
3579 profile_index < mHwModules[module_index]->mInputProfiles.size();
3580 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003581 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003582 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003583 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003584 profile_index, module_index);
3585 if (profile->mSamplingRates[0] == 0) {
3586 profile->mSamplingRates.clear();
3587 profile->mSamplingRates.add(0);
3588 }
3589 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3590 profile->mFormats.clear();
3591 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3592 }
3593 if (profile->mChannelMasks[0] == 0) {
3594 profile->mChannelMasks.clear();
3595 profile->mChannelMasks.add(0);
3596 }
3597 }
3598 }
3599 }
3600 } // end disconnect
3601
3602 return NO_ERROR;
3603}
3604
3605
Eric Laurente0720872014-03-11 09:30:41 -07003606void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003607{
3608 ALOGV("closeOutput(%d)", output);
3609
Eric Laurent1f2f2232014-06-02 12:01:23 -07003610 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003611 if (outputDesc == NULL) {
3612 ALOGW("closeOutput() unknown output %d", output);
3613 return;
3614 }
3615
3616 // look for duplicated outputs connected to the output being removed.
3617 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003618 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003619 if (dupOutputDesc->isDuplicated() &&
3620 (dupOutputDesc->mOutput1 == outputDesc ||
3621 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003622 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003623 if (dupOutputDesc->mOutput1 == outputDesc) {
3624 outputDesc2 = dupOutputDesc->mOutput2;
3625 } else {
3626 outputDesc2 = dupOutputDesc->mOutput1;
3627 }
3628 // As all active tracks on duplicated output will be deleted,
3629 // and as they were also referenced on the other output, the reference
3630 // count for their stream type must be adjusted accordingly on
3631 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003632 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003633 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003634 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003635 }
3636 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3637 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3638
3639 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003640 mOutputs.removeItem(duplicatedOutput);
3641 }
3642 }
3643
Eric Laurent05b90f82014-08-27 15:32:29 -07003644 nextAudioPortGeneration();
3645
3646 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3647 if (index >= 0) {
3648 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3649 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3650 mAudioPatches.removeItemsAt(index);
3651 mpClientInterface->onAudioPatchListUpdate();
3652 }
3653
Eric Laurente552edb2014-03-10 17:42:56 -07003654 AudioParameter param;
3655 param.add(String8("closing"), String8("true"));
3656 mpClientInterface->setParameters(output, param.toString());
3657
3658 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003659 mOutputs.removeItem(output);
3660 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003661}
3662
3663void AudioPolicyManager::closeInput(audio_io_handle_t input)
3664{
3665 ALOGV("closeInput(%d)", input);
3666
3667 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3668 if (inputDesc == NULL) {
3669 ALOGW("closeInput() unknown input %d", input);
3670 return;
3671 }
3672
Eric Laurent6a94d692014-05-20 11:18:06 -07003673 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003674
3675 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3676 if (index >= 0) {
3677 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3678 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3679 mAudioPatches.removeItemsAt(index);
3680 mpClientInterface->onAudioPatchListUpdate();
3681 }
3682
3683 mpClientInterface->closeInput(input);
3684 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003685}
3686
Eric Laurente0720872014-03-11 09:30:41 -07003687SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003688 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003689{
3690 SortedVector<audio_io_handle_t> outputs;
3691
3692 ALOGVV("getOutputsForDevice() device %04x", device);
3693 for (size_t i = 0; i < openOutputs.size(); i++) {
3694 ALOGVV("output %d isDuplicated=%d device=%04x",
3695 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3696 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3697 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3698 outputs.add(openOutputs.keyAt(i));
3699 }
3700 }
3701 return outputs;
3702}
3703
Eric Laurente0720872014-03-11 09:30:41 -07003704bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003705 SortedVector<audio_io_handle_t>& outputs2)
3706{
3707 if (outputs1.size() != outputs2.size()) {
3708 return false;
3709 }
3710 for (size_t i = 0; i < outputs1.size(); i++) {
3711 if (outputs1[i] != outputs2[i]) {
3712 return false;
3713 }
3714 }
3715 return true;
3716}
3717
Eric Laurente0720872014-03-11 09:30:41 -07003718void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003719{
3720 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3721 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3722 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3723 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3724
3725 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3726 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3727 strategy, srcOutputs[0], dstOutputs[0]);
3728 // mute strategy while moving tracks from one output to another
3729 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003730 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003731 if (desc->isStrategyActive(strategy)) {
3732 setStrategyMute(strategy, true, srcOutputs[i]);
3733 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3734 }
3735 }
3736
3737 // Move effects associated to this strategy from previous output to new output
3738 if (strategy == STRATEGY_MEDIA) {
3739 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3740 SortedVector<audio_io_handle_t> moved;
3741 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003742 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3743 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3744 effectDesc->mIo != fxOutput) {
3745 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003746 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3747 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003748 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003749 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003750 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003751 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003752 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003753 }
3754 }
3755 }
3756 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003757 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3758 if (getStrategy((audio_stream_type_t)i) == strategy) {
3759 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003760 }
3761 }
3762 }
3763}
3764
Eric Laurente0720872014-03-11 09:30:41 -07003765void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003766{
Jon Eklund966095e2014-09-09 15:39:49 -05003767 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3768 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003769 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05003770 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3771 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003772 checkOutputForStrategy(STRATEGY_SONIFICATION);
3773 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3774 checkOutputForStrategy(STRATEGY_MEDIA);
3775 checkOutputForStrategy(STRATEGY_DTMF);
3776}
3777
Eric Laurente0720872014-03-11 09:30:41 -07003778audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003779{
Eric Laurente552edb2014-03-10 17:42:56 -07003780 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003781 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003782 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3783 return mOutputs.keyAt(i);
3784 }
3785 }
3786
3787 return 0;
3788}
3789
Eric Laurente0720872014-03-11 09:30:41 -07003790void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003791{
Eric Laurente552edb2014-03-10 17:42:56 -07003792 audio_io_handle_t a2dpOutput = getA2dpOutput();
3793 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003794 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003795 return;
3796 }
3797
Eric Laurent3a4311c2014-03-17 12:00:47 -07003798 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08003799 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
3800 ~AUDIO_DEVICE_BIT_IN) != 0) ||
3801 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07003802 // suspend A2DP output if:
3803 // (NOT already suspended) &&
3804 // ((SCO device is connected &&
3805 // (forced usage for communication || for record is SCO))) ||
3806 // (phone state is ringing || in call)
3807 //
3808 // restore A2DP output if:
3809 // (Already suspended) &&
3810 // ((SCO device is NOT connected ||
3811 // (forced usage NOT for communication && NOT for record is SCO))) &&
3812 // (phone state is NOT ringing && NOT in call)
3813 //
3814 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003815 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003816 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3817 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3818 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3819 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003820
3821 mpClientInterface->restoreOutput(a2dpOutput);
3822 mA2dpSuspended = false;
3823 }
3824 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003825 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003826 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3827 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3828 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3829 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003830
3831 mpClientInterface->suspendOutput(a2dpOutput);
3832 mA2dpSuspended = true;
3833 }
3834 }
3835}
3836
Eric Laurent1c333e22014-05-20 10:48:17 -07003837audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003838{
3839 audio_devices_t device = AUDIO_DEVICE_NONE;
3840
Eric Laurent1f2f2232014-06-02 12:01:23 -07003841 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003842
3843 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3844 if (index >= 0) {
3845 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3846 if (patchDesc->mUid != mUidCached) {
3847 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3848 outputDesc->device(), outputDesc->mPatchHandle);
3849 return outputDesc->device();
3850 }
3851 }
3852
Eric Laurente552edb2014-03-10 17:42:56 -07003853 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05003854 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003855 // use device for strategy enforced audible
3856 // 2: we are in call or the strategy phone is active on the output:
3857 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05003858 // 3: the strategy for enforced audible is active but not enforced on the output:
3859 // use the device for strategy enforced audible
3860 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003861 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003862 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003863 // use device for strategy "respectful" sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003864 // 6: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003865 // use device for strategy media
Jon Eklund966095e2014-09-09 15:39:49 -05003866 // 7: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003867 // use device for strategy DTMF
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003868 // 8: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
3869 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05003870 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
3871 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07003872 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3873 } else if (isInCall() ||
3874 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3875 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05003876 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3877 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003878 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3879 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3880 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3881 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3882 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3883 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3884 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3885 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003886 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
3887 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003888 }
3889
Eric Laurent1c333e22014-05-20 10:48:17 -07003890 ALOGV("getNewOutputDevice() selected device %x", device);
3891 return device;
3892}
3893
3894audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3895{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003896 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003897
3898 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3899 if (index >= 0) {
3900 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3901 if (patchDesc->mUid != mUidCached) {
3902 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3903 inputDesc->mDevice, inputDesc->mPatchHandle);
3904 return inputDesc->mDevice;
3905 }
3906 }
3907
Eric Laurent1c333e22014-05-20 10:48:17 -07003908 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3909
3910 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003911 return device;
3912}
3913
Eric Laurente0720872014-03-11 09:30:41 -07003914uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003915 return (uint32_t)getStrategy(stream);
3916}
3917
Eric Laurente0720872014-03-11 09:30:41 -07003918audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003919 // By checking the range of stream before calling getStrategy, we avoid
3920 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3921 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003922 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003923 return AUDIO_DEVICE_NONE;
3924 }
3925 audio_devices_t devices;
3926 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3927 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3928 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3929 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003930 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003931 if (outputDesc->isStrategyActive(strategy)) {
3932 devices = outputDesc->device();
3933 break;
3934 }
Eric Laurente552edb2014-03-10 17:42:56 -07003935 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05003936
3937 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
3938 and doesn't really need to.*/
3939 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
3940 devices |= AUDIO_DEVICE_OUT_SPEAKER;
3941 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
3942 }
3943
Eric Laurente552edb2014-03-10 17:42:56 -07003944 return devices;
3945}
3946
Eric Laurente0720872014-03-11 09:30:41 -07003947AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003948 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003949 // stream to strategy mapping
3950 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003951 case AUDIO_STREAM_VOICE_CALL:
3952 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003953 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003954 case AUDIO_STREAM_RING:
3955 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003956 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003957 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003958 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003959 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003960 return STRATEGY_DTMF;
3961 default:
3962 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003963 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003964 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3965 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003966 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003967 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003968 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003969 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003970 case AUDIO_STREAM_TTS:
3971 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003972 }
3973}
3974
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003975uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3976 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003977 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
3978 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
3979 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003980 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3981 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3982 }
3983
3984 // usage to strategy mapping
3985 switch (attr->usage) {
3986 case AUDIO_USAGE_MEDIA:
3987 case AUDIO_USAGE_GAME:
3988 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3989 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3990 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3991 return (uint32_t) STRATEGY_MEDIA;
3992
3993 case AUDIO_USAGE_VOICE_COMMUNICATION:
3994 return (uint32_t) STRATEGY_PHONE;
3995
3996 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3997 return (uint32_t) STRATEGY_DTMF;
3998
3999 case AUDIO_USAGE_ALARM:
4000 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4001 return (uint32_t) STRATEGY_SONIFICATION;
4002
4003 case AUDIO_USAGE_NOTIFICATION:
4004 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4005 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4006 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4007 case AUDIO_USAGE_NOTIFICATION_EVENT:
4008 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4009
4010 case AUDIO_USAGE_UNKNOWN:
4011 default:
4012 return (uint32_t) STRATEGY_MEDIA;
4013 }
4014}
4015
Eric Laurente0720872014-03-11 09:30:41 -07004016void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004017 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004018 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004019 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4020 updateDevicesAndOutputs();
4021 break;
4022 default:
4023 break;
4024 }
4025}
4026
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004027bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4028 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4029 if (s == (size_t) streamToIgnore) {
4030 continue;
4031 }
4032 for (size_t i = 0; i < mOutputs.size(); i++) {
4033 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4034 if (outputDesc->mRefCount[s] != 0) {
4035 return true;
4036 }
4037 }
4038 }
4039 return false;
4040}
4041
4042uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4043 switch(event) {
4044 case STARTING_OUTPUT:
4045 mBeaconMuteRefCount++;
4046 break;
4047 case STOPPING_OUTPUT:
4048 if (mBeaconMuteRefCount > 0) {
4049 mBeaconMuteRefCount--;
4050 }
4051 break;
4052 case STARTING_BEACON:
4053 mBeaconPlayingRefCount++;
4054 break;
4055 case STOPPING_BEACON:
4056 if (mBeaconPlayingRefCount > 0) {
4057 mBeaconPlayingRefCount--;
4058 }
4059 break;
4060 }
4061
4062 if (mBeaconMuteRefCount > 0) {
4063 // any playback causes beacon to be muted
4064 return setBeaconMute(true);
4065 } else {
4066 // no other playback: unmute when beacon starts playing, mute when it stops
4067 return setBeaconMute(mBeaconPlayingRefCount == 0);
4068 }
4069}
4070
4071uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4072 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4073 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4074 // keep track of muted state to avoid repeating mute/unmute operations
4075 if (mBeaconMuted != mute) {
4076 // mute/unmute AUDIO_STREAM_TTS on all outputs
4077 ALOGV("\t muting %d", mute);
4078 uint32_t maxLatency = 0;
4079 for (size_t i = 0; i < mOutputs.size(); i++) {
4080 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4081 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4082 desc->mIoHandle,
4083 0 /*delay*/, AUDIO_DEVICE_NONE);
4084 const uint32_t latency = desc->latency() * 2;
4085 if (latency > maxLatency) {
4086 maxLatency = latency;
4087 }
4088 }
4089 mBeaconMuted = mute;
4090 return maxLatency;
4091 }
4092 return 0;
4093}
4094
Eric Laurente0720872014-03-11 09:30:41 -07004095audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004096 bool fromCache)
4097{
4098 uint32_t device = AUDIO_DEVICE_NONE;
4099
4100 if (fromCache) {
4101 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4102 strategy, mDeviceForStrategy[strategy]);
4103 return mDeviceForStrategy[strategy];
4104 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004105 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004106 switch (strategy) {
4107
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004108 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4109 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4110 if (!device) {
4111 ALOGE("getDeviceForStrategy() no device found for "\
4112 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4113 }
4114 break;
4115
Eric Laurente552edb2014-03-10 17:42:56 -07004116 case STRATEGY_SONIFICATION_RESPECTFUL:
4117 if (isInCall()) {
4118 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004119 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004120 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4121 // while media is playing on a remote device, use the the sonification behavior.
4122 // Note that we test this usecase before testing if media is playing because
4123 // the isStreamActive() method only informs about the activity of a stream, not
4124 // if it's for local playback. Note also that we use the same delay between both tests
4125 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004126 //user "safe" speaker if available instead of normal speaker to avoid triggering
4127 //other acoustic safety mechanisms for notification
4128 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4129 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004130 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004131 // while media is playing (or has recently played), use the same device
4132 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4133 } else {
4134 // when media is not playing anymore, fall back on the sonification behavior
4135 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004136 //user "safe" speaker if available instead of normal speaker to avoid triggering
4137 //other acoustic safety mechanisms for notification
4138 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4139 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004140 }
4141
4142 break;
4143
4144 case STRATEGY_DTMF:
4145 if (!isInCall()) {
4146 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4147 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4148 break;
4149 }
4150 // when in call, DTMF and PHONE strategies follow the same rules
4151 // FALL THROUGH
4152
4153 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004154 // Force use of only devices on primary output if:
4155 // - in call AND
4156 // - cannot route from voice call RX OR
4157 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4158 if (mPhoneState == AUDIO_MODE_IN_CALL) {
4159 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4160 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4161 if (((mAvailableInputDevices.types() &
4162 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4163 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004164 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004165 AUDIO_DEVICE_API_VERSION_3_0))) {
4166 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4167 }
4168 }
Eric Laurente552edb2014-03-10 17:42:56 -07004169 // for phone strategy, we first consider the forced use and then the available devices by order
4170 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004171 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4172 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004173 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004174 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004175 if (device) break;
4176 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004177 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004178 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004179 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004180 if (device) break;
4181 // if SCO device is requested but no SCO device is available, fall back to default case
4182 // FALL THROUGH
4183
4184 default: // FORCE_NONE
4185 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004186 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004187 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004188 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004189 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004190 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004191 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004192 if (device) break;
4193 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004194 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004195 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004196 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004197 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004198 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4199 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004200 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004201 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004202 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004203 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004204 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004205 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004206 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004207 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004208 if (device) break;
4209 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004210 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004211 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004212 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004213 if (device == AUDIO_DEVICE_NONE) {
4214 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4215 }
4216 break;
4217
Eric Laurent3b73df72014-03-11 09:06:29 -07004218 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004219 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4220 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004221 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004222 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004223 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004224 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004225 if (device) break;
4226 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004227 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004228 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004229 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004230 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004231 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004232 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004233 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004234 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004235 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004236 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004237 if (device) break;
4238 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004239 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4240 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004241 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004242 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004243 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004244 if (device == AUDIO_DEVICE_NONE) {
4245 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4246 }
4247 break;
4248 }
4249 break;
4250
4251 case STRATEGY_SONIFICATION:
4252
4253 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4254 // handleIncallSonification().
4255 if (isInCall()) {
4256 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4257 break;
4258 }
4259 // FALL THROUGH
4260
4261 case STRATEGY_ENFORCED_AUDIBLE:
4262 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4263 // except:
4264 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4265 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4266
4267 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004268 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004269 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004270 if (device == AUDIO_DEVICE_NONE) {
4271 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4272 }
4273 }
4274 // The second device used for sonification is the same as the device used by media strategy
4275 // FALL THROUGH
4276
4277 case STRATEGY_MEDIA: {
4278 uint32_t device2 = AUDIO_DEVICE_NONE;
4279 if (strategy != STRATEGY_SONIFICATION) {
4280 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004281 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004282 }
4283 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004284 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004285 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004286 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004287 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004288 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004289 }
4290 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004291 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004292 }
4293 }
Hochi Huang327cb702014-09-21 09:47:31 +08004294 if ((device2 == AUDIO_DEVICE_NONE) &&
4295 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4296 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4297 }
Eric Laurente552edb2014-03-10 17:42:56 -07004298 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004299 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004300 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004301 if ((device2 == AUDIO_DEVICE_NONE)) {
4302 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4303 }
Eric Laurente552edb2014-03-10 17:42:56 -07004304 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004305 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004306 }
4307 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004308 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004309 }
4310 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004311 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004312 }
4313 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004314 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004315 }
4316 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4317 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004318 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004319 }
4320 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004321 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004322 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004323 }
4324 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004325 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004326 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004327 int device3 = AUDIO_DEVICE_NONE;
4328 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004329 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004330 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4331 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004332 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004333 }
Eric Laurente552edb2014-03-10 17:42:56 -07004334
Jungshik Jang839e4f32014-06-26 17:23:40 +09004335 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004336 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4337 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4338 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004339
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004340 // If hdmi system audio mode is on, remove speaker out of output list.
4341 if ((strategy == STRATEGY_MEDIA) &&
4342 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4343 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4344 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4345 }
4346
Eric Laurente552edb2014-03-10 17:42:56 -07004347 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004348 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004349 if (device == AUDIO_DEVICE_NONE) {
4350 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4351 }
4352 } break;
4353
4354 default:
4355 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4356 break;
4357 }
4358
4359 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4360 return device;
4361}
4362
Eric Laurente0720872014-03-11 09:30:41 -07004363void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004364{
4365 for (int i = 0; i < NUM_STRATEGIES; i++) {
4366 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4367 }
4368 mPreviousOutputs = mOutputs;
4369}
4370
Eric Laurent1f2f2232014-06-02 12:01:23 -07004371uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004372 audio_devices_t prevDevice,
4373 uint32_t delayMs)
4374{
4375 // mute/unmute strategies using an incompatible device combination
4376 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4377 // if unmuting, unmute only after the specified delay
4378 if (outputDesc->isDuplicated()) {
4379 return 0;
4380 }
4381
4382 uint32_t muteWaitMs = 0;
4383 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004384 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004385
4386 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4387 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004388 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004389 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4390 bool doMute = false;
4391
4392 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4393 doMute = true;
4394 outputDesc->mStrategyMutedByDevice[i] = true;
4395 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4396 doMute = true;
4397 outputDesc->mStrategyMutedByDevice[i] = false;
4398 }
Eric Laurent99401132014-05-07 19:48:15 -07004399 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004400 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004401 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004402 // skip output if it does not share any device with current output
4403 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4404 == AUDIO_DEVICE_NONE) {
4405 continue;
4406 }
4407 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4408 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4409 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4410 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4411 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004412 if (mute) {
4413 // FIXME: should not need to double latency if volume could be applied
4414 // immediately by the audioflinger mixer. We must account for the delay
4415 // between now and the next time the audioflinger thread for this output
4416 // will process a buffer (which corresponds to one buffer size,
4417 // usually 1/2 or 1/4 of the latency).
4418 if (muteWaitMs < desc->latency() * 2) {
4419 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004420 }
4421 }
4422 }
4423 }
4424 }
4425 }
4426
Eric Laurent99401132014-05-07 19:48:15 -07004427 // temporary mute output if device selection changes to avoid volume bursts due to
4428 // different per device volumes
4429 if (outputDesc->isActive() && (device != prevDevice)) {
4430 if (muteWaitMs < outputDesc->latency() * 2) {
4431 muteWaitMs = outputDesc->latency() * 2;
4432 }
4433 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4434 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004435 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004436 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004437 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004438 muteWaitMs *2, device);
4439 }
4440 }
4441 }
4442
Eric Laurente552edb2014-03-10 17:42:56 -07004443 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4444 if (muteWaitMs > delayMs) {
4445 muteWaitMs -= delayMs;
4446 usleep(muteWaitMs * 1000);
4447 return muteWaitMs;
4448 }
4449 return 0;
4450}
4451
Eric Laurente0720872014-03-11 09:30:41 -07004452uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004453 audio_devices_t device,
4454 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004455 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004456 audio_patch_handle_t *patchHandle,
4457 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004458{
4459 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004460 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004461 AudioParameter param;
4462 uint32_t muteWaitMs;
4463
4464 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004465 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4466 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004467 return muteWaitMs;
4468 }
4469 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4470 // output profile
4471 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004472 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004473 return 0;
4474 }
4475
4476 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004477 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004478
4479 audio_devices_t prevDevice = outputDesc->mDevice;
4480
4481 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4482
4483 if (device != AUDIO_DEVICE_NONE) {
4484 outputDesc->mDevice = device;
4485 }
4486 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4487
4488 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004489 // the requested device is AUDIO_DEVICE_NONE
4490 // OR the requested device is the same as current device
4491 // AND force is not specified
4492 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004493 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004494 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4495 outputDesc->mPatchHandle != 0) {
4496 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4497 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004498 return muteWaitMs;
4499 }
4500
4501 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004502
Eric Laurente552edb2014-03-10 17:42:56 -07004503 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004504 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004505 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004506 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004507 DeviceVector deviceList = (address == NULL) ?
4508 mAvailableOutputDevices.getDevicesFromType(device)
4509 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004510 if (!deviceList.isEmpty()) {
4511 struct audio_patch patch;
4512 outputDesc->toAudioPortConfig(&patch.sources[0]);
4513 patch.num_sources = 1;
4514 patch.num_sinks = 0;
4515 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4516 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004517 patch.num_sinks++;
4518 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004519 ssize_t index;
4520 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4521 index = mAudioPatches.indexOfKey(*patchHandle);
4522 } else {
4523 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4524 }
4525 sp< AudioPatch> patchDesc;
4526 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4527 if (index >= 0) {
4528 patchDesc = mAudioPatches.valueAt(index);
4529 afPatchHandle = patchDesc->mAfPatchHandle;
4530 }
4531
Eric Laurent1c333e22014-05-20 10:48:17 -07004532 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004533 &afPatchHandle,
4534 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004535 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4536 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004537 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004538 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004539 if (index < 0) {
4540 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4541 &patch, mUidCached);
4542 addAudioPatch(patchDesc->mHandle, patchDesc);
4543 } else {
4544 patchDesc->mPatch = patch;
4545 }
4546 patchDesc->mAfPatchHandle = afPatchHandle;
4547 patchDesc->mUid = mUidCached;
4548 if (patchHandle) {
4549 *patchHandle = patchDesc->mHandle;
4550 }
4551 outputDesc->mPatchHandle = patchDesc->mHandle;
4552 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004553 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004554 }
4555 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004556
4557 // inform all input as well
4558 for (size_t i = 0; i < mInputs.size(); i++) {
4559 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4560 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4561 AudioParameter inputCmd = AudioParameter();
4562 ALOGV("%s: inform input %d of device:%d", __func__,
4563 inputDescriptor->mIoHandle, device);
4564 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4565 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4566 inputCmd.toString(),
4567 delayMs);
4568 }
4569 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004570 }
Eric Laurente552edb2014-03-10 17:42:56 -07004571
4572 // update stream volumes according to new device
4573 applyStreamVolumes(output, device, delayMs);
4574
4575 return muteWaitMs;
4576}
4577
Eric Laurent1c333e22014-05-20 10:48:17 -07004578status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004579 int delayMs,
4580 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004581{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004582 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004583 ssize_t index;
4584 if (patchHandle) {
4585 index = mAudioPatches.indexOfKey(*patchHandle);
4586 } else {
4587 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4588 }
4589 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004590 return INVALID_OPERATION;
4591 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004592 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4593 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004594 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4595 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004596 removeAudioPatch(patchDesc->mHandle);
4597 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004598 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004599 return status;
4600}
4601
4602status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4603 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004604 bool force,
4605 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004606{
4607 status_t status = NO_ERROR;
4608
Eric Laurent1f2f2232014-06-02 12:01:23 -07004609 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004610 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4611 inputDesc->mDevice = device;
4612
4613 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4614 if (!deviceList.isEmpty()) {
4615 struct audio_patch patch;
4616 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004617 // AUDIO_SOURCE_HOTWORD is for internal use only:
4618 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004619 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4620 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004621 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4622 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004623 patch.num_sinks = 1;
4624 //only one input device for now
4625 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004626 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004627 ssize_t index;
4628 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4629 index = mAudioPatches.indexOfKey(*patchHandle);
4630 } else {
4631 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4632 }
4633 sp< AudioPatch> patchDesc;
4634 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4635 if (index >= 0) {
4636 patchDesc = mAudioPatches.valueAt(index);
4637 afPatchHandle = patchDesc->mAfPatchHandle;
4638 }
4639
Eric Laurent1c333e22014-05-20 10:48:17 -07004640 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004641 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004642 0);
4643 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004644 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004645 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004646 if (index < 0) {
4647 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4648 &patch, mUidCached);
4649 addAudioPatch(patchDesc->mHandle, patchDesc);
4650 } else {
4651 patchDesc->mPatch = patch;
4652 }
4653 patchDesc->mAfPatchHandle = afPatchHandle;
4654 patchDesc->mUid = mUidCached;
4655 if (patchHandle) {
4656 *patchHandle = patchDesc->mHandle;
4657 }
4658 inputDesc->mPatchHandle = patchDesc->mHandle;
4659 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004660 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004661 }
4662 }
4663 }
4664 return status;
4665}
4666
Eric Laurent6a94d692014-05-20 11:18:06 -07004667status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4668 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004669{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004670 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004671 ssize_t index;
4672 if (patchHandle) {
4673 index = mAudioPatches.indexOfKey(*patchHandle);
4674 } else {
4675 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4676 }
4677 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004678 return INVALID_OPERATION;
4679 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004680 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4681 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004682 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4683 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004684 removeAudioPatch(patchDesc->mHandle);
4685 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004686 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004687 return status;
4688}
4689
4690sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004691 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004692 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004693 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004694 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004695{
4696 // Choose an input profile based on the requested capture parameters: select the first available
4697 // profile supporting all requested parameters.
4698
4699 for (size_t i = 0; i < mHwModules.size(); i++)
4700 {
4701 if (mHwModules[i]->mHandle == 0) {
4702 continue;
4703 }
4704 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4705 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004706 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004707 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004708 if (profile->isCompatibleProfile(device, samplingRate,
4709 &samplingRate /*updatedSamplingRate*/,
4710 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004711 return profile;
4712 }
4713 }
4714 }
4715 return NULL;
4716}
4717
Eric Laurente0720872014-03-11 09:30:41 -07004718audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004719{
4720 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004721 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4722 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004723 switch (inputSource) {
4724 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004725 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004726 device = AUDIO_DEVICE_IN_VOICE_CALL;
4727 break;
4728 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004729 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004730
4731 case AUDIO_SOURCE_DEFAULT:
4732 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004733 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4734 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004735 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4736 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4737 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4738 device = AUDIO_DEVICE_IN_USB_DEVICE;
4739 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4740 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004741 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004742 break;
4743
4744 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4745 // Allow only use of devices on primary input if in call and HAL does not support routing
4746 // to voice call path.
4747 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4748 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4749 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4750 }
4751
4752 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4753 case AUDIO_POLICY_FORCE_BT_SCO:
4754 // if SCO device is requested but no SCO device is available, fall back to default case
4755 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4756 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4757 break;
4758 }
4759 // FALL THROUGH
4760
4761 default: // FORCE_NONE
4762 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4763 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4764 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4765 device = AUDIO_DEVICE_IN_USB_DEVICE;
4766 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4767 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4768 }
4769 break;
4770
4771 case AUDIO_POLICY_FORCE_SPEAKER:
4772 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4773 device = AUDIO_DEVICE_IN_BACK_MIC;
4774 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4775 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4776 }
4777 break;
4778 }
4779 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004780
Eric Laurente552edb2014-03-10 17:42:56 -07004781 case AUDIO_SOURCE_VOICE_RECOGNITION:
4782 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004783 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004784 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004785 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004786 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004787 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004788 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4789 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004790 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004791 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4792 }
4793 break;
4794 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004795 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004796 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004797 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004798 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4799 }
4800 break;
4801 case AUDIO_SOURCE_VOICE_DOWNLINK:
4802 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004803 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004804 device = AUDIO_DEVICE_IN_VOICE_CALL;
4805 }
4806 break;
4807 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004808 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004809 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4810 }
4811 break;
Hochi Huang327cb702014-09-21 09:47:31 +08004812 case AUDIO_SOURCE_FM_TUNER:
4813 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
4814 device = AUDIO_DEVICE_IN_FM_TUNER;
4815 }
4816 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004817 default:
4818 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4819 break;
4820 }
4821 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4822 return device;
4823}
4824
Eric Laurente0720872014-03-11 09:30:41 -07004825bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004826{
4827 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4828 device &= ~AUDIO_DEVICE_BIT_IN;
4829 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4830 return true;
4831 }
4832 return false;
4833}
4834
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004835bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4836 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4837}
4838
Eric Laurente0720872014-03-11 09:30:41 -07004839audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004840{
4841 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004842 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004843 if ((input_descriptor->mRefCount > 0)
4844 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4845 return mInputs.keyAt(i);
4846 }
4847 }
4848 return 0;
4849}
4850
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004851uint32_t AudioPolicyManager::activeInputsCount() const
4852{
4853 uint32_t count = 0;
4854 for (size_t i = 0; i < mInputs.size(); i++) {
4855 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4856 if (desc->mRefCount > 0) {
4857 return count++;
4858 }
4859 }
4860 return count;
4861}
4862
Eric Laurente552edb2014-03-10 17:42:56 -07004863
Eric Laurente0720872014-03-11 09:30:41 -07004864audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004865{
4866 if (device == AUDIO_DEVICE_NONE) {
4867 // this happens when forcing a route update and no track is active on an output.
4868 // In this case the returned category is not important.
4869 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004870 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004871 // Multiple device selection is either:
4872 // - speaker + one other device: give priority to speaker in this case.
4873 // - one A2DP device + another device: happens with duplicated output. In this case
4874 // retain the device on the A2DP output as the other must not correspond to an active
4875 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004876 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004877 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4878 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004879 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4880 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4881 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4882 device = AUDIO_DEVICE_OUT_AUX_LINE;
4883 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4884 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004885 } else {
4886 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4887 }
4888 }
4889
Jon Eklund11c9fb12014-06-23 14:47:03 -05004890 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4891 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4892 device = AUDIO_DEVICE_OUT_SPEAKER;
4893
Eric Laurent3b73df72014-03-11 09:06:29 -07004894 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004895 "getDeviceForVolume() invalid device combination: %08x",
4896 device);
4897
4898 return device;
4899}
4900
Eric Laurente0720872014-03-11 09:30:41 -07004901AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004902{
4903 switch(getDeviceForVolume(device)) {
4904 case AUDIO_DEVICE_OUT_EARPIECE:
4905 return DEVICE_CATEGORY_EARPIECE;
4906 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4907 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4908 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4909 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4910 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4911 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4912 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004913 case AUDIO_DEVICE_OUT_LINE:
4914 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4915 /*USB? Remote submix?*/
4916 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004917 case AUDIO_DEVICE_OUT_SPEAKER:
4918 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4919 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004920 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4921 case AUDIO_DEVICE_OUT_USB_DEVICE:
4922 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4923 default:
4924 return DEVICE_CATEGORY_SPEAKER;
4925 }
4926}
4927
Eric Laurente0720872014-03-11 09:30:41 -07004928float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004929 int indexInUi)
4930{
4931 device_category deviceCategory = getDeviceCategory(device);
4932 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4933
4934 // the volume index in the UI is relative to the min and max volume indices for this stream type
4935 int nbSteps = 1 + curve[VOLMAX].mIndex -
4936 curve[VOLMIN].mIndex;
4937 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4938 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4939
4940 // find what part of the curve this index volume belongs to, or if it's out of bounds
4941 int segment = 0;
4942 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4943 return 0.0f;
4944 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4945 segment = 0;
4946 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4947 segment = 1;
4948 } else if (volIdx <= curve[VOLMAX].mIndex) {
4949 segment = 2;
4950 } else { // out of bounds
4951 return 1.0f;
4952 }
4953
4954 // linear interpolation in the attenuation table in dB
4955 float decibels = curve[segment].mDBAttenuation +
4956 ((float)(volIdx - curve[segment].mIndex)) *
4957 ( (curve[segment+1].mDBAttenuation -
4958 curve[segment].mDBAttenuation) /
4959 ((float)(curve[segment+1].mIndex -
4960 curve[segment].mIndex)) );
4961
4962 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4963
4964 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4965 curve[segment].mIndex, volIdx,
4966 curve[segment+1].mIndex,
4967 curve[segment].mDBAttenuation,
4968 decibels,
4969 curve[segment+1].mDBAttenuation,
4970 amplification);
4971
4972 return amplification;
4973}
4974
Eric Laurente0720872014-03-11 09:30:41 -07004975const AudioPolicyManager::VolumeCurvePoint
4976 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004977 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4978};
4979
Eric Laurente0720872014-03-11 09:30:41 -07004980const AudioPolicyManager::VolumeCurvePoint
4981 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004982 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4983};
4984
Eric Laurente0720872014-03-11 09:30:41 -07004985const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004986 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4987 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4988};
4989
4990const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004991 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004992 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4993};
4994
Eric Laurente0720872014-03-11 09:30:41 -07004995const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004996 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004997 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004998};
4999
5000const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005001 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005002 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5003};
5004
Eric Laurente0720872014-03-11 09:30:41 -07005005const AudioPolicyManager::VolumeCurvePoint
5006 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005007 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5008};
5009
5010// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5011// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5012// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5013// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5014
Eric Laurente0720872014-03-11 09:30:41 -07005015const AudioPolicyManager::VolumeCurvePoint
5016 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005017 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5018};
5019
Eric Laurente0720872014-03-11 09:30:41 -07005020const AudioPolicyManager::VolumeCurvePoint
5021 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005022 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5023};
5024
Eric Laurente0720872014-03-11 09:30:41 -07005025const AudioPolicyManager::VolumeCurvePoint
5026 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005027 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5028};
5029
Eric Laurente0720872014-03-11 09:30:41 -07005030const AudioPolicyManager::VolumeCurvePoint
5031 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005032 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5033};
5034
Eric Laurente0720872014-03-11 09:30:41 -07005035const AudioPolicyManager::VolumeCurvePoint
5036 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005037 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5038};
5039
Eric Laurente0720872014-03-11 09:30:41 -07005040const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005041 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5042 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5043};
5044
5045const AudioPolicyManager::VolumeCurvePoint
5046 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5047 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5048};
5049
5050const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005051 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5052 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005053 { // AUDIO_STREAM_VOICE_CALL
5054 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5055 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005056 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5057 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005058 },
5059 { // AUDIO_STREAM_SYSTEM
5060 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5061 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005062 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5063 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005064 },
5065 { // AUDIO_STREAM_RING
5066 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5067 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005068 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5069 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005070 },
5071 { // AUDIO_STREAM_MUSIC
5072 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5073 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005074 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5075 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005076 },
5077 { // AUDIO_STREAM_ALARM
5078 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5079 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005080 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5081 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005082 },
5083 { // AUDIO_STREAM_NOTIFICATION
5084 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5085 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005086 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5087 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005088 },
5089 { // AUDIO_STREAM_BLUETOOTH_SCO
5090 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5091 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005092 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5093 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005094 },
5095 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5096 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5097 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005098 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5099 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005100 },
5101 { // AUDIO_STREAM_DTMF
5102 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5103 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005104 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5105 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005106 },
5107 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005108 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5109 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5110 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5111 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5112 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005113 },
5114};
5115
Eric Laurente0720872014-03-11 09:30:41 -07005116void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005117{
5118 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5119 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5120 mStreams[i].mVolumeCurve[j] =
5121 sVolumeProfiles[i][j];
5122 }
5123 }
5124
5125 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5126 if (mSpeakerDrcEnabled) {
5127 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5128 sDefaultSystemVolumeCurveDrc;
5129 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5130 sSpeakerSonificationVolumeCurveDrc;
5131 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5132 sSpeakerSonificationVolumeCurveDrc;
5133 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5134 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005135 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5136 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005137 }
5138}
5139
Eric Laurente0720872014-03-11 09:30:41 -07005140float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005141 int index,
5142 audio_io_handle_t output,
5143 audio_devices_t device)
5144{
5145 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005146 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005147 StreamDescriptor &streamDesc = mStreams[stream];
5148
5149 if (device == AUDIO_DEVICE_NONE) {
5150 device = outputDesc->device();
5151 }
5152
Eric Laurente552edb2014-03-10 17:42:56 -07005153 volume = volIndexToAmpl(device, streamDesc, index);
5154
5155 // if a headset is connected, apply the following rules to ring tones and notifications
5156 // to avoid sound level bursts in user's ears:
5157 // - always attenuate ring tones and notifications volume by 6dB
5158 // - if music is playing, always limit the volume to current music volume,
5159 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005160 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005161 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5162 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5163 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5164 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5165 ((stream_strategy == STRATEGY_SONIFICATION)
5166 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005167 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005168 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005169 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005170 streamDesc.mCanBeMuted) {
5171 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5172 // when the phone is ringing we must consider that music could have been paused just before
5173 // by the music application and behave as if music was active if the last music track was
5174 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005175 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005176 mLimitRingtoneVolume) {
5177 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005178 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5179 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005180 output,
5181 musicDevice);
5182 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5183 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5184 if (volume > minVol) {
5185 volume = minVol;
5186 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5187 }
5188 }
5189 }
5190
5191 return volume;
5192}
5193
Eric Laurente0720872014-03-11 09:30:41 -07005194status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005195 int index,
5196 audio_io_handle_t output,
5197 audio_devices_t device,
5198 int delayMs,
5199 bool force)
5200{
5201
5202 // do not change actual stream volume if the stream is muted
5203 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5204 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5205 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5206 return NO_ERROR;
5207 }
5208
5209 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005210 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5211 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5212 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5213 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005214 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005215 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005216 return INVALID_OPERATION;
5217 }
5218
5219 float volume = computeVolume(stream, index, output, device);
5220 // We actually change the volume if:
5221 // - the float value returned by computeVolume() changed
5222 // - the force flag is set
5223 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5224 force) {
5225 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5226 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5227 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5228 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005229 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5230 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005231 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005232 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005233 }
5234
Eric Laurent3b73df72014-03-11 09:06:29 -07005235 if (stream == AUDIO_STREAM_VOICE_CALL ||
5236 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005237 float voiceVolume;
5238 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005239 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005240 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5241 } else {
5242 voiceVolume = 1.0;
5243 }
5244
5245 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5246 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5247 mLastVoiceVolume = voiceVolume;
5248 }
5249 }
5250
5251 return NO_ERROR;
5252}
5253
Eric Laurente0720872014-03-11 09:30:41 -07005254void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005255 audio_devices_t device,
5256 int delayMs,
5257 bool force)
5258{
5259 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5260
Eric Laurent3b73df72014-03-11 09:06:29 -07005261 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5262 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005263 mStreams[stream].getVolumeIndex(device),
5264 output,
5265 device,
5266 delayMs,
5267 force);
5268 }
5269}
5270
Eric Laurente0720872014-03-11 09:30:41 -07005271void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005272 bool on,
5273 audio_io_handle_t output,
5274 int delayMs,
5275 audio_devices_t device)
5276{
5277 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005278 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5279 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5280 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005281 }
5282 }
5283}
5284
Eric Laurente0720872014-03-11 09:30:41 -07005285void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005286 bool on,
5287 audio_io_handle_t output,
5288 int delayMs,
5289 audio_devices_t device)
5290{
5291 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005292 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005293 if (device == AUDIO_DEVICE_NONE) {
5294 device = outputDesc->device();
5295 }
5296
5297 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5298 stream, on, output, outputDesc->mMuteCount[stream], device);
5299
5300 if (on) {
5301 if (outputDesc->mMuteCount[stream] == 0) {
5302 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005303 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5304 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005305 checkAndSetVolume(stream, 0, output, device, delayMs);
5306 }
5307 }
5308 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5309 outputDesc->mMuteCount[stream]++;
5310 } else {
5311 if (outputDesc->mMuteCount[stream] == 0) {
5312 ALOGV("setStreamMute() unmuting non muted stream!");
5313 return;
5314 }
5315 if (--outputDesc->mMuteCount[stream] == 0) {
5316 checkAndSetVolume(stream,
5317 streamDesc.getVolumeIndex(device),
5318 output,
5319 device,
5320 delayMs);
5321 }
5322 }
5323}
5324
Eric Laurente0720872014-03-11 09:30:41 -07005325void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005326 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005327{
5328 // if the stream pertains to sonification strategy and we are in call we must
5329 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5330 // in the device used for phone strategy and play the tone if the selected device does not
5331 // interfere with the device used for phone strategy
5332 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5333 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005334 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005335 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5336 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005337 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005338 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5339 stream, starting, outputDesc->mDevice, stateChange);
5340 if (outputDesc->mRefCount[stream]) {
5341 int muteCount = 1;
5342 if (stateChange) {
5343 muteCount = outputDesc->mRefCount[stream];
5344 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005345 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005346 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5347 for (int i = 0; i < muteCount; i++) {
5348 setStreamMute(stream, starting, mPrimaryOutput);
5349 }
5350 } else {
5351 ALOGV("handleIncallSonification() high visibility");
5352 if (outputDesc->device() &
5353 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5354 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5355 for (int i = 0; i < muteCount; i++) {
5356 setStreamMute(stream, starting, mPrimaryOutput);
5357 }
5358 }
5359 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005360 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5361 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005362 } else {
5363 mpClientInterface->stopTone();
5364 }
5365 }
5366 }
5367 }
5368}
5369
Eric Laurente0720872014-03-11 09:30:41 -07005370bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005371{
5372 return isStateInCall(mPhoneState);
5373}
5374
Eric Laurente0720872014-03-11 09:30:41 -07005375bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005376 return ((state == AUDIO_MODE_IN_CALL) ||
5377 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005378}
5379
Eric Laurente0720872014-03-11 09:30:41 -07005380uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005381{
5382 return MAX_EFFECTS_CPU_LOAD;
5383}
5384
Eric Laurente0720872014-03-11 09:30:41 -07005385uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005386{
5387 return MAX_EFFECTS_MEMORY;
5388}
5389
Eric Laurent6a94d692014-05-20 11:18:06 -07005390
Eric Laurente552edb2014-03-10 17:42:56 -07005391// --- AudioOutputDescriptor class implementation
5392
Eric Laurente0720872014-03-11 09:30:41 -07005393AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005394 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005395 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005396 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005397 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5398{
5399 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005400 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005401 mRefCount[i] = 0;
5402 mCurVolume[i] = -1.0;
5403 mMuteCount[i] = 0;
5404 mStopTime[i] = 0;
5405 }
5406 for (int i = 0; i < NUM_STRATEGIES; i++) {
5407 mStrategyMutedByDevice[i] = false;
5408 }
5409 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005410 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005411 mSamplingRate = profile->pickSamplingRate();
5412 mFormat = profile->pickFormat();
5413 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005414 if (profile->mGains.size() > 0) {
5415 profile->mGains[0]->getDefaultConfig(&mGain);
5416 }
Eric Laurente552edb2014-03-10 17:42:56 -07005417 }
5418}
5419
Eric Laurente0720872014-03-11 09:30:41 -07005420audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005421{
5422 if (isDuplicated()) {
5423 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5424 } else {
5425 return mDevice;
5426 }
5427}
5428
Eric Laurente0720872014-03-11 09:30:41 -07005429uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005430{
5431 if (isDuplicated()) {
5432 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5433 } else {
5434 return mLatency;
5435 }
5436}
5437
Eric Laurente0720872014-03-11 09:30:41 -07005438bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005439 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005440{
5441 if (isDuplicated()) {
5442 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5443 } else if (outputDesc->isDuplicated()){
5444 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5445 } else {
5446 return (mProfile->mModule == outputDesc->mProfile->mModule);
5447 }
5448}
5449
Eric Laurente0720872014-03-11 09:30:41 -07005450void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005451 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005452{
5453 // forward usage count change to attached outputs
5454 if (isDuplicated()) {
5455 mOutput1->changeRefCount(stream, delta);
5456 mOutput2->changeRefCount(stream, delta);
5457 }
5458 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005459 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5460 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005461 mRefCount[stream] = 0;
5462 return;
5463 }
5464 mRefCount[stream] += delta;
5465 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5466}
5467
Eric Laurente0720872014-03-11 09:30:41 -07005468audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005469{
5470 if (isDuplicated()) {
5471 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5472 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005473 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005474 }
5475}
5476
Eric Laurente0720872014-03-11 09:30:41 -07005477bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005478{
5479 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5480}
5481
Eric Laurente0720872014-03-11 09:30:41 -07005482bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005483 uint32_t inPastMs,
5484 nsecs_t sysTime) const
5485{
5486 if ((sysTime == 0) && (inPastMs != 0)) {
5487 sysTime = systemTime();
5488 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005489 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5490 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005491 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005492 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005493 return true;
5494 }
5495 }
5496 return false;
5497}
5498
Eric Laurente0720872014-03-11 09:30:41 -07005499bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005500 uint32_t inPastMs,
5501 nsecs_t sysTime) const
5502{
5503 if (mRefCount[stream] != 0) {
5504 return true;
5505 }
5506 if (inPastMs == 0) {
5507 return false;
5508 }
5509 if (sysTime == 0) {
5510 sysTime = systemTime();
5511 }
5512 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5513 return true;
5514 }
5515 return false;
5516}
5517
Eric Laurent1c333e22014-05-20 10:48:17 -07005518void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005519 struct audio_port_config *dstConfig,
5520 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005521{
Eric Laurent84c70242014-06-23 08:46:27 -07005522 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5523
Eric Laurent1f2f2232014-06-02 12:01:23 -07005524 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5525 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5526 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005527 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005528 }
5529 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5530
Eric Laurent6a94d692014-05-20 11:18:06 -07005531 dstConfig->id = mId;
5532 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5533 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005534 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5535 dstConfig->ext.mix.handle = mIoHandle;
5536 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005537}
5538
5539void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5540 struct audio_port *port) const
5541{
Eric Laurent84c70242014-06-23 08:46:27 -07005542 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005543 mProfile->toAudioPort(port);
5544 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005545 toAudioPortConfig(&port->active_config);
5546 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005547 port->ext.mix.handle = mIoHandle;
5548 port->ext.mix.latency_class =
5549 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5550}
Eric Laurente552edb2014-03-10 17:42:56 -07005551
Eric Laurente0720872014-03-11 09:30:41 -07005552status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005553{
5554 const size_t SIZE = 256;
5555 char buffer[SIZE];
5556 String8 result;
5557
Eric Laurent4d416952014-08-10 14:07:09 -07005558 snprintf(buffer, SIZE, " ID: %d\n", mId);
5559 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005560 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5561 result.append(buffer);
5562 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5563 result.append(buffer);
5564 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5565 result.append(buffer);
5566 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5567 result.append(buffer);
5568 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5569 result.append(buffer);
5570 snprintf(buffer, SIZE, " Devices %08x\n", device());
5571 result.append(buffer);
5572 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5573 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005574 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5575 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5576 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005577 result.append(buffer);
5578 }
5579 write(fd, result.string(), result.size());
5580
5581 return NO_ERROR;
5582}
5583
5584// --- AudioInputDescriptor class implementation
5585
Eric Laurent1c333e22014-05-20 10:48:17 -07005586AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005587 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005588 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005589 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005590{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005591 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005592 mSamplingRate = profile->pickSamplingRate();
5593 mFormat = profile->pickFormat();
5594 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005595 if (profile->mGains.size() > 0) {
5596 profile->mGains[0]->getDefaultConfig(&mGain);
5597 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005598 }
Eric Laurente552edb2014-03-10 17:42:56 -07005599}
5600
Eric Laurent1c333e22014-05-20 10:48:17 -07005601void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005602 struct audio_port_config *dstConfig,
5603 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005604{
Eric Laurent84c70242014-06-23 08:46:27 -07005605 ALOG_ASSERT(mProfile != 0,
5606 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005607 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5608 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5609 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005610 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005611 }
5612
5613 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5614
Eric Laurent6a94d692014-05-20 11:18:06 -07005615 dstConfig->id = mId;
5616 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5617 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005618 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5619 dstConfig->ext.mix.handle = mIoHandle;
5620 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005621}
5622
5623void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5624 struct audio_port *port) const
5625{
Eric Laurent84c70242014-06-23 08:46:27 -07005626 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5627
Eric Laurent1c333e22014-05-20 10:48:17 -07005628 mProfile->toAudioPort(port);
5629 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005630 toAudioPortConfig(&port->active_config);
5631 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005632 port->ext.mix.handle = mIoHandle;
5633 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5634}
5635
Eric Laurente0720872014-03-11 09:30:41 -07005636status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005637{
5638 const size_t SIZE = 256;
5639 char buffer[SIZE];
5640 String8 result;
5641
Eric Laurent4d416952014-08-10 14:07:09 -07005642 snprintf(buffer, SIZE, " ID: %d\n", mId);
5643 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005644 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5645 result.append(buffer);
5646 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5647 result.append(buffer);
5648 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5649 result.append(buffer);
5650 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5651 result.append(buffer);
5652 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5653 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005654 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5655 result.append(buffer);
5656
Eric Laurente552edb2014-03-10 17:42:56 -07005657 write(fd, result.string(), result.size());
5658
5659 return NO_ERROR;
5660}
5661
5662// --- StreamDescriptor class implementation
5663
Eric Laurente0720872014-03-11 09:30:41 -07005664AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005665 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5666{
5667 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5668}
5669
Eric Laurente0720872014-03-11 09:30:41 -07005670int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005671{
Eric Laurente0720872014-03-11 09:30:41 -07005672 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005673 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5674 if (mIndexCur.indexOfKey(device) < 0) {
5675 device = AUDIO_DEVICE_OUT_DEFAULT;
5676 }
5677 return mIndexCur.valueFor(device);
5678}
5679
Eric Laurente0720872014-03-11 09:30:41 -07005680void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005681{
5682 const size_t SIZE = 256;
5683 char buffer[SIZE];
5684 String8 result;
5685
5686 snprintf(buffer, SIZE, "%s %02d %02d ",
5687 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5688 result.append(buffer);
5689 for (size_t i = 0; i < mIndexCur.size(); i++) {
5690 snprintf(buffer, SIZE, "%04x : %02d, ",
5691 mIndexCur.keyAt(i),
5692 mIndexCur.valueAt(i));
5693 result.append(buffer);
5694 }
5695 result.append("\n");
5696
5697 write(fd, result.string(), result.size());
5698}
5699
5700// --- EffectDescriptor class implementation
5701
Eric Laurente0720872014-03-11 09:30:41 -07005702status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005703{
5704 const size_t SIZE = 256;
5705 char buffer[SIZE];
5706 String8 result;
5707
5708 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5709 result.append(buffer);
5710 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5711 result.append(buffer);
5712 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5713 result.append(buffer);
5714 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5715 result.append(buffer);
5716 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5717 result.append(buffer);
5718 write(fd, result.string(), result.size());
5719
5720 return NO_ERROR;
5721}
5722
Eric Laurent1c333e22014-05-20 10:48:17 -07005723// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005724
Eric Laurente0720872014-03-11 09:30:41 -07005725AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005726 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5727 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005728{
5729}
5730
Eric Laurente0720872014-03-11 09:30:41 -07005731AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005732{
5733 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005734 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005735 }
5736 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005737 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005738 }
5739 free((void *)mName);
5740}
5741
Eric Laurent1afeecb2014-05-14 08:52:28 -07005742status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5743{
5744 cnode *node = root->first_child;
5745
5746 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5747
5748 while (node) {
5749 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5750 profile->loadSamplingRates((char *)node->value);
5751 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5752 profile->loadFormats((char *)node->value);
5753 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5754 profile->loadInChannels((char *)node->value);
5755 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5756 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5757 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07005758 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5759 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005760 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5761 profile->loadGains(node);
5762 }
5763 node = node->next;
5764 }
5765 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5766 "loadInput() invalid supported devices");
5767 ALOGW_IF(profile->mChannelMasks.size() == 0,
5768 "loadInput() invalid supported channel masks");
5769 ALOGW_IF(profile->mSamplingRates.size() == 0,
5770 "loadInput() invalid supported sampling rates");
5771 ALOGW_IF(profile->mFormats.size() == 0,
5772 "loadInput() invalid supported formats");
5773 if (!profile->mSupportedDevices.isEmpty() &&
5774 (profile->mChannelMasks.size() != 0) &&
5775 (profile->mSamplingRates.size() != 0) &&
5776 (profile->mFormats.size() != 0)) {
5777
5778 ALOGV("loadInput() adding input Supported Devices %04x",
5779 profile->mSupportedDevices.types());
5780
5781 mInputProfiles.add(profile);
5782 return NO_ERROR;
5783 } else {
5784 return BAD_VALUE;
5785 }
5786}
5787
5788status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5789{
5790 cnode *node = root->first_child;
5791
5792 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5793
5794 while (node) {
5795 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5796 profile->loadSamplingRates((char *)node->value);
5797 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5798 profile->loadFormats((char *)node->value);
5799 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5800 profile->loadOutChannels((char *)node->value);
5801 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5802 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5803 mDeclaredDevices);
5804 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005805 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005806 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5807 profile->loadGains(node);
5808 }
5809 node = node->next;
5810 }
5811 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5812 "loadOutput() invalid supported devices");
5813 ALOGW_IF(profile->mChannelMasks.size() == 0,
5814 "loadOutput() invalid supported channel masks");
5815 ALOGW_IF(profile->mSamplingRates.size() == 0,
5816 "loadOutput() invalid supported sampling rates");
5817 ALOGW_IF(profile->mFormats.size() == 0,
5818 "loadOutput() invalid supported formats");
5819 if (!profile->mSupportedDevices.isEmpty() &&
5820 (profile->mChannelMasks.size() != 0) &&
5821 (profile->mSamplingRates.size() != 0) &&
5822 (profile->mFormats.size() != 0)) {
5823
5824 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5825 profile->mSupportedDevices.types(), profile->mFlags);
5826
5827 mOutputProfiles.add(profile);
5828 return NO_ERROR;
5829 } else {
5830 return BAD_VALUE;
5831 }
5832}
5833
5834status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5835{
5836 cnode *node = root->first_child;
5837
5838 audio_devices_t type = AUDIO_DEVICE_NONE;
5839 while (node) {
5840 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5841 type = parseDeviceNames((char *)node->value);
5842 break;
5843 }
5844 node = node->next;
5845 }
5846 if (type == AUDIO_DEVICE_NONE ||
5847 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5848 ALOGW("loadDevice() bad type %08x", type);
5849 return BAD_VALUE;
5850 }
5851 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5852 deviceDesc->mModule = this;
5853
5854 node = root->first_child;
5855 while (node) {
5856 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5857 deviceDesc->mAddress = String8((char *)node->value);
5858 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5859 if (audio_is_input_device(type)) {
5860 deviceDesc->loadInChannels((char *)node->value);
5861 } else {
5862 deviceDesc->loadOutChannels((char *)node->value);
5863 }
5864 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5865 deviceDesc->loadGains(node);
5866 }
5867 node = node->next;
5868 }
5869
5870 ALOGV("loadDevice() adding device name %s type %08x address %s",
5871 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5872
5873 mDeclaredDevices.add(deviceDesc);
5874
5875 return NO_ERROR;
5876}
5877
Eric Laurente0720872014-03-11 09:30:41 -07005878void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005879{
5880 const size_t SIZE = 256;
5881 char buffer[SIZE];
5882 String8 result;
5883
5884 snprintf(buffer, SIZE, " - name: %s\n", mName);
5885 result.append(buffer);
5886 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5887 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005888 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5889 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005890 write(fd, result.string(), result.size());
5891 if (mOutputProfiles.size()) {
5892 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5893 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005894 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005895 write(fd, buffer, strlen(buffer));
5896 mOutputProfiles[i]->dump(fd);
5897 }
5898 }
5899 if (mInputProfiles.size()) {
5900 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5901 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005902 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005903 write(fd, buffer, strlen(buffer));
5904 mInputProfiles[i]->dump(fd);
5905 }
5906 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005907 if (mDeclaredDevices.size()) {
5908 write(fd, " - devices:\n", strlen(" - devices:\n"));
5909 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5910 mDeclaredDevices[i]->dump(fd, 4, i);
5911 }
5912 }
Eric Laurente552edb2014-03-10 17:42:56 -07005913}
5914
Eric Laurent1c333e22014-05-20 10:48:17 -07005915// --- AudioPort class implementation
5916
Eric Laurenta121f902014-06-03 13:32:54 -07005917
5918AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5919 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07005920 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07005921{
5922 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5923 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5924}
5925
Eric Laurent1c333e22014-05-20 10:48:17 -07005926void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5927{
5928 port->role = mRole;
5929 port->type = mType;
5930 unsigned int i;
5931 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005932 if (mSamplingRates[i] != 0) {
5933 port->sample_rates[i] = mSamplingRates[i];
5934 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005935 }
5936 port->num_sample_rates = i;
5937 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005938 if (mChannelMasks[i] != 0) {
5939 port->channel_masks[i] = mChannelMasks[i];
5940 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005941 }
5942 port->num_channel_masks = i;
5943 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005944 if (mFormats[i] != 0) {
5945 port->formats[i] = mFormats[i];
5946 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005947 }
5948 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005949
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005950 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005951
5952 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5953 port->gains[i] = mGains[i]->mGain;
5954 }
5955 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005956}
5957
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005958void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
5959 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
5960 const uint32_t rate = port->mSamplingRates.itemAt(k);
5961 if (rate != 0) { // skip "dynamic" rates
5962 bool hasRate = false;
5963 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
5964 if (rate == mSamplingRates.itemAt(l)) {
5965 hasRate = true;
5966 break;
5967 }
5968 }
5969 if (!hasRate) { // never import a sampling rate twice
5970 mSamplingRates.add(rate);
5971 }
5972 }
5973 }
5974 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
5975 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
5976 if (mask != 0) { // skip "dynamic" masks
5977 bool hasMask = false;
5978 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
5979 if (mask == mChannelMasks.itemAt(l)) {
5980 hasMask = true;
5981 break;
5982 }
5983 }
5984 if (!hasMask) { // never import a channel mask twice
5985 mChannelMasks.add(mask);
5986 }
5987 }
5988 }
5989 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
5990 const audio_format_t format = port->mFormats.itemAt(k);
5991 if (format != 0) { // skip "dynamic" formats
5992 bool hasFormat = false;
5993 for (size_t l = 0 ; l < mFormats.size() ; l++) {
5994 if (format == mFormats.itemAt(l)) {
5995 hasFormat = true;
5996 break;
5997 }
5998 }
5999 if (!hasFormat) { // never import a channel mask twice
6000 mFormats.add(format);
6001 }
6002 }
6003 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006004 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6005 sp<AudioGain> gain = port->mGains.itemAt(k);
6006 if (gain != 0) {
6007 bool hasGain = false;
6008 for (size_t l = 0 ; l < mGains.size() ; l++) {
6009 if (gain == mGains.itemAt(l)) {
6010 hasGain = true;
6011 break;
6012 }
6013 }
6014 if (!hasGain) { // never import a gain twice
6015 mGains.add(gain);
6016 }
6017 }
6018 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006019}
6020
6021void AudioPolicyManager::AudioPort::clearCapabilities() {
6022 mChannelMasks.clear();
6023 mFormats.clear();
6024 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006025 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006026}
Eric Laurent1c333e22014-05-20 10:48:17 -07006027
6028void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6029{
6030 char *str = strtok(name, "|");
6031
6032 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6033 // rates should be read from the output stream after it is opened for the first time
6034 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6035 mSamplingRates.add(0);
6036 return;
6037 }
6038
6039 while (str != NULL) {
6040 uint32_t rate = atoi(str);
6041 if (rate != 0) {
6042 ALOGV("loadSamplingRates() adding rate %d", rate);
6043 mSamplingRates.add(rate);
6044 }
6045 str = strtok(NULL, "|");
6046 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006047}
6048
6049void AudioPolicyManager::AudioPort::loadFormats(char *name)
6050{
6051 char *str = strtok(name, "|");
6052
6053 // by convention, "0' in the first entry in mFormats indicates the supported formats
6054 // should be read from the output stream after it is opened for the first time
6055 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6056 mFormats.add(AUDIO_FORMAT_DEFAULT);
6057 return;
6058 }
6059
6060 while (str != NULL) {
6061 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6062 ARRAY_SIZE(sFormatNameToEnumTable),
6063 str);
6064 if (format != AUDIO_FORMAT_DEFAULT) {
6065 mFormats.add(format);
6066 }
6067 str = strtok(NULL, "|");
6068 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006069}
6070
6071void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6072{
6073 const char *str = strtok(name, "|");
6074
6075 ALOGV("loadInChannels() %s", name);
6076
6077 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6078 mChannelMasks.add(0);
6079 return;
6080 }
6081
6082 while (str != NULL) {
6083 audio_channel_mask_t channelMask =
6084 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6085 ARRAY_SIZE(sInChannelsNameToEnumTable),
6086 str);
6087 if (channelMask != 0) {
6088 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6089 mChannelMasks.add(channelMask);
6090 }
6091 str = strtok(NULL, "|");
6092 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006093}
6094
6095void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6096{
6097 const char *str = strtok(name, "|");
6098
6099 ALOGV("loadOutChannels() %s", name);
6100
6101 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6102 // masks should be read from the output stream after it is opened for the first time
6103 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6104 mChannelMasks.add(0);
6105 return;
6106 }
6107
6108 while (str != NULL) {
6109 audio_channel_mask_t channelMask =
6110 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6111 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6112 str);
6113 if (channelMask != 0) {
6114 mChannelMasks.add(channelMask);
6115 }
6116 str = strtok(NULL, "|");
6117 }
6118 return;
6119}
6120
Eric Laurent1afeecb2014-05-14 08:52:28 -07006121audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6122{
6123 const char *str = strtok(name, "|");
6124
6125 ALOGV("loadGainMode() %s", name);
6126 audio_gain_mode_t mode = 0;
6127 while (str != NULL) {
6128 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6129 ARRAY_SIZE(sGainModeNameToEnumTable),
6130 str);
6131 str = strtok(NULL, "|");
6132 }
6133 return mode;
6134}
6135
Eric Laurenta121f902014-06-03 13:32:54 -07006136void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006137{
6138 cnode *node = root->first_child;
6139
Eric Laurenta121f902014-06-03 13:32:54 -07006140 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006141
6142 while (node) {
6143 if (strcmp(node->name, GAIN_MODE) == 0) {
6144 gain->mGain.mode = loadGainMode((char *)node->value);
6145 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006146 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006147 gain->mGain.channel_mask =
6148 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6149 ARRAY_SIZE(sInChannelsNameToEnumTable),
6150 (char *)node->value);
6151 } else {
6152 gain->mGain.channel_mask =
6153 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6154 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6155 (char *)node->value);
6156 }
6157 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6158 gain->mGain.min_value = atoi((char *)node->value);
6159 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6160 gain->mGain.max_value = atoi((char *)node->value);
6161 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6162 gain->mGain.default_value = atoi((char *)node->value);
6163 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6164 gain->mGain.step_value = atoi((char *)node->value);
6165 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6166 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6167 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6168 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6169 }
6170 node = node->next;
6171 }
6172
6173 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6174 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6175
6176 if (gain->mGain.mode == 0) {
6177 return;
6178 }
6179 mGains.add(gain);
6180}
6181
6182void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6183{
6184 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006185 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006186 while (node) {
6187 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006188 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006189 node = node->next;
6190 }
6191}
6192
Glenn Kastencbd48022014-07-24 13:46:44 -07006193status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006194{
6195 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6196 if (mSamplingRates[i] == samplingRate) {
6197 return NO_ERROR;
6198 }
6199 }
6200 return BAD_VALUE;
6201}
6202
Glenn Kastencbd48022014-07-24 13:46:44 -07006203status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6204 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006205{
Glenn Kastencbd48022014-07-24 13:46:44 -07006206 // Search for the closest supported sampling rate that is above (preferred)
6207 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6208 // The sampling rates do not need to be sorted in ascending order.
6209 ssize_t maxBelow = -1;
6210 ssize_t minAbove = -1;
6211 uint32_t candidate;
6212 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6213 candidate = mSamplingRates[i];
6214 if (candidate == samplingRate) {
6215 if (updatedSamplingRate != NULL) {
6216 *updatedSamplingRate = candidate;
6217 }
6218 return NO_ERROR;
6219 }
6220 // candidate < desired
6221 if (candidate < samplingRate) {
6222 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6223 maxBelow = i;
6224 }
6225 // candidate > desired
6226 } else {
6227 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6228 minAbove = i;
6229 }
6230 }
6231 }
6232 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6233 // TODO Move these assumptions out.
6234 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6235 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6236 // due to approximation by an int32_t of the
6237 // phase increments
6238 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6239 if (minAbove >= 0) {
6240 candidate = mSamplingRates[minAbove];
6241 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6242 if (updatedSamplingRate != NULL) {
6243 *updatedSamplingRate = candidate;
6244 }
6245 return NO_ERROR;
6246 }
6247 }
6248 // But if we have to up-sample from a lower sampling rate, that's OK.
6249 if (maxBelow >= 0) {
6250 candidate = mSamplingRates[maxBelow];
6251 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6252 if (updatedSamplingRate != NULL) {
6253 *updatedSamplingRate = candidate;
6254 }
6255 return NO_ERROR;
6256 }
6257 }
6258 // leave updatedSamplingRate unmodified
6259 return BAD_VALUE;
6260}
6261
6262status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6263{
6264 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006265 if (mChannelMasks[i] == channelMask) {
6266 return NO_ERROR;
6267 }
6268 }
6269 return BAD_VALUE;
6270}
6271
Glenn Kastencbd48022014-07-24 13:46:44 -07006272status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6273 const
6274{
6275 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6276 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6277 // FIXME Does not handle multi-channel automatic conversions yet
6278 audio_channel_mask_t supported = mChannelMasks[i];
6279 if (supported == channelMask) {
6280 return NO_ERROR;
6281 }
6282 if (isRecordThread) {
6283 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6284 // FIXME Abstract this out to a table.
6285 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6286 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6287 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6288 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6289 return NO_ERROR;
6290 }
6291 }
6292 }
6293 return BAD_VALUE;
6294}
6295
Eric Laurenta121f902014-06-03 13:32:54 -07006296status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6297{
6298 for (size_t i = 0; i < mFormats.size(); i ++) {
6299 if (mFormats[i] == format) {
6300 return NO_ERROR;
6301 }
6302 }
6303 return BAD_VALUE;
6304}
6305
Eric Laurent1e693b52014-07-09 15:03:28 -07006306
6307uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6308{
6309 // special case for uninitialized dynamic profile
6310 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6311 return 0;
6312 }
6313
Eric Laurent828bcff2014-09-07 12:26:06 -07006314 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6315 // channel count / sampling rate combination chosen will be supported by the connected
6316 // sink
6317 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6318 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6319 uint32_t samplingRate = UINT_MAX;
6320 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6321 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6322 samplingRate = mSamplingRates[i];
6323 }
6324 }
6325 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6326 }
6327
Eric Laurent1e693b52014-07-09 15:03:28 -07006328 uint32_t samplingRate = 0;
6329 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6330
6331 // For mixed output and inputs, use max mixer sampling rates. Do not
6332 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006333 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006334 maxRate = UINT_MAX;
6335 }
6336 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6337 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6338 samplingRate = mSamplingRates[i];
6339 }
6340 }
6341 return samplingRate;
6342}
6343
6344audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6345{
6346 // special case for uninitialized dynamic profile
6347 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6348 return AUDIO_CHANNEL_NONE;
6349 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006350 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006351
6352 // For direct outputs, pick minimum channel count: this helps ensuring that the
6353 // channel count / sampling rate combination chosen will be supported by the connected
6354 // sink
6355 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6356 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6357 uint32_t channelCount = UINT_MAX;
6358 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6359 uint32_t cnlCount;
6360 if (mUseInChannelMask) {
6361 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6362 } else {
6363 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6364 }
6365 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6366 channelMask = mChannelMasks[i];
6367 channelCount = cnlCount;
6368 }
6369 }
6370 return channelMask;
6371 }
6372
Eric Laurent1e693b52014-07-09 15:03:28 -07006373 uint32_t channelCount = 0;
6374 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6375
6376 // For mixed output and inputs, use max mixer channel count. Do not
6377 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006378 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006379 maxCount = UINT_MAX;
6380 }
6381 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6382 uint32_t cnlCount;
6383 if (mUseInChannelMask) {
6384 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6385 } else {
6386 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6387 }
6388 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6389 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006390 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006391 }
6392 }
6393 return channelMask;
6394}
6395
Andy Hung9a605382014-07-28 16:16:31 -07006396/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006397const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6398 AUDIO_FORMAT_DEFAULT,
6399 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006400 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006401 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006402 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006403 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006404};
6405
6406int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6407 audio_format_t format2)
6408{
6409 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6410 // compressed format and better than any PCM format. This is by design of pickFormat()
6411 if (!audio_is_linear_pcm(format1)) {
6412 if (!audio_is_linear_pcm(format2)) {
6413 return 0;
6414 }
6415 return 1;
6416 }
6417 if (!audio_is_linear_pcm(format2)) {
6418 return -1;
6419 }
6420
6421 int index1 = -1, index2 = -1;
6422 for (size_t i = 0;
6423 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6424 i ++) {
6425 if (sPcmFormatCompareTable[i] == format1) {
6426 index1 = i;
6427 }
6428 if (sPcmFormatCompareTable[i] == format2) {
6429 index2 = i;
6430 }
6431 }
6432 // format1 not found => index1 < 0 => format2 > format1
6433 // format2 not found => index2 < 0 => format2 < format1
6434 return index1 - index2;
6435}
6436
6437audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6438{
6439 // special case for uninitialized dynamic profile
6440 if (mFormats.size() == 1 && mFormats[0] == 0) {
6441 return AUDIO_FORMAT_DEFAULT;
6442 }
6443
6444 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006445 audio_format_t bestFormat =
6446 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6447 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006448 // For mixed output and inputs, use best mixer output format. Do not
6449 // limit format otherwise
6450 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6451 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006452 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006453 bestFormat = AUDIO_FORMAT_INVALID;
6454 }
6455
6456 for (size_t i = 0; i < mFormats.size(); i ++) {
6457 if ((compareFormats(mFormats[i], format) > 0) &&
6458 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6459 format = mFormats[i];
6460 }
6461 }
6462 return format;
6463}
6464
Eric Laurenta121f902014-06-03 13:32:54 -07006465status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6466 int index) const
6467{
6468 if (index < 0 || (size_t)index >= mGains.size()) {
6469 return BAD_VALUE;
6470 }
6471 return mGains[index]->checkConfig(gainConfig);
6472}
6473
Eric Laurent1afeecb2014-05-14 08:52:28 -07006474void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6475{
6476 const size_t SIZE = 256;
6477 char buffer[SIZE];
6478 String8 result;
6479
6480 if (mName.size() != 0) {
6481 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6482 result.append(buffer);
6483 }
6484
6485 if (mSamplingRates.size() != 0) {
6486 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6487 result.append(buffer);
6488 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006489 if (i == 0 && mSamplingRates[i] == 0) {
6490 snprintf(buffer, SIZE, "Dynamic");
6491 } else {
6492 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6493 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006494 result.append(buffer);
6495 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6496 }
6497 result.append("\n");
6498 }
6499
6500 if (mChannelMasks.size() != 0) {
6501 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6502 result.append(buffer);
6503 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006504 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6505
6506 if (i == 0 && mChannelMasks[i] == 0) {
6507 snprintf(buffer, SIZE, "Dynamic");
6508 } else {
6509 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6510 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006511 result.append(buffer);
6512 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6513 }
6514 result.append("\n");
6515 }
6516
6517 if (mFormats.size() != 0) {
6518 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6519 result.append(buffer);
6520 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006521 const char *formatStr = enumToString(sFormatNameToEnumTable,
6522 ARRAY_SIZE(sFormatNameToEnumTable),
6523 mFormats[i]);
6524 if (i == 0 && strcmp(formatStr, "") == 0) {
6525 snprintf(buffer, SIZE, "Dynamic");
6526 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006527 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006528 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006529 result.append(buffer);
6530 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6531 }
6532 result.append("\n");
6533 }
6534 write(fd, result.string(), result.size());
6535 if (mGains.size() != 0) {
6536 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6537 write(fd, buffer, strlen(buffer) + 1);
6538 result.append(buffer);
6539 for (size_t i = 0; i < mGains.size(); i++) {
6540 mGains[i]->dump(fd, spaces + 2, i);
6541 }
6542 }
6543}
6544
6545// --- AudioGain class implementation
6546
Eric Laurenta121f902014-06-03 13:32:54 -07006547AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006548{
Eric Laurenta121f902014-06-03 13:32:54 -07006549 mIndex = index;
6550 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006551 memset(&mGain, 0, sizeof(struct audio_gain));
6552}
6553
Eric Laurenta121f902014-06-03 13:32:54 -07006554void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6555{
6556 config->index = mIndex;
6557 config->mode = mGain.mode;
6558 config->channel_mask = mGain.channel_mask;
6559 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6560 config->values[0] = mGain.default_value;
6561 } else {
6562 uint32_t numValues;
6563 if (mUseInChannelMask) {
6564 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6565 } else {
6566 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6567 }
6568 for (size_t i = 0; i < numValues; i++) {
6569 config->values[i] = mGain.default_value;
6570 }
6571 }
6572 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6573 config->ramp_duration_ms = mGain.min_ramp_ms;
6574 }
6575}
6576
6577status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6578{
6579 if ((config->mode & ~mGain.mode) != 0) {
6580 return BAD_VALUE;
6581 }
6582 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6583 if ((config->values[0] < mGain.min_value) ||
6584 (config->values[0] > mGain.max_value)) {
6585 return BAD_VALUE;
6586 }
6587 } else {
6588 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6589 return BAD_VALUE;
6590 }
6591 uint32_t numValues;
6592 if (mUseInChannelMask) {
6593 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6594 } else {
6595 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6596 }
6597 for (size_t i = 0; i < numValues; i++) {
6598 if ((config->values[i] < mGain.min_value) ||
6599 (config->values[i] > mGain.max_value)) {
6600 return BAD_VALUE;
6601 }
6602 }
6603 }
6604 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6605 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6606 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6607 return BAD_VALUE;
6608 }
6609 }
6610 return NO_ERROR;
6611}
6612
Eric Laurent1afeecb2014-05-14 08:52:28 -07006613void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6614{
6615 const size_t SIZE = 256;
6616 char buffer[SIZE];
6617 String8 result;
6618
6619 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6620 result.append(buffer);
6621 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6622 result.append(buffer);
6623 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6624 result.append(buffer);
6625 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6626 result.append(buffer);
6627 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6628 result.append(buffer);
6629 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6630 result.append(buffer);
6631 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6632 result.append(buffer);
6633 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6634 result.append(buffer);
6635 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6636 result.append(buffer);
6637
6638 write(fd, result.string(), result.size());
6639}
6640
Eric Laurent1f2f2232014-06-02 12:01:23 -07006641// --- AudioPortConfig class implementation
6642
6643AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6644{
6645 mSamplingRate = 0;
6646 mChannelMask = AUDIO_CHANNEL_NONE;
6647 mFormat = AUDIO_FORMAT_INVALID;
6648 mGain.index = -1;
6649}
6650
Eric Laurenta121f902014-06-03 13:32:54 -07006651status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6652 const struct audio_port_config *config,
6653 struct audio_port_config *backupConfig)
6654{
6655 struct audio_port_config localBackupConfig;
6656 status_t status = NO_ERROR;
6657
6658 localBackupConfig.config_mask = config->config_mask;
6659 toAudioPortConfig(&localBackupConfig);
6660
Marco Nelissen961ec212014-08-25 15:58:39 -07006661 sp<AudioPort> audioport = getAudioPort();
6662 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006663 status = NO_INIT;
6664 goto exit;
6665 }
6666 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006667 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006668 if (status != NO_ERROR) {
6669 goto exit;
6670 }
6671 mSamplingRate = config->sample_rate;
6672 }
6673 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006674 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006675 if (status != NO_ERROR) {
6676 goto exit;
6677 }
6678 mChannelMask = config->channel_mask;
6679 }
6680 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006681 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006682 if (status != NO_ERROR) {
6683 goto exit;
6684 }
6685 mFormat = config->format;
6686 }
6687 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006688 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006689 if (status != NO_ERROR) {
6690 goto exit;
6691 }
6692 mGain = config->gain;
6693 }
6694
6695exit:
6696 if (status != NO_ERROR) {
6697 applyAudioPortConfig(&localBackupConfig);
6698 }
6699 if (backupConfig != NULL) {
6700 *backupConfig = localBackupConfig;
6701 }
6702 return status;
6703}
6704
Eric Laurent1f2f2232014-06-02 12:01:23 -07006705void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6706 struct audio_port_config *dstConfig,
6707 const struct audio_port_config *srcConfig) const
6708{
6709 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6710 dstConfig->sample_rate = mSamplingRate;
6711 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6712 dstConfig->sample_rate = srcConfig->sample_rate;
6713 }
6714 } else {
6715 dstConfig->sample_rate = 0;
6716 }
6717 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6718 dstConfig->channel_mask = mChannelMask;
6719 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6720 dstConfig->channel_mask = srcConfig->channel_mask;
6721 }
6722 } else {
6723 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6724 }
6725 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6726 dstConfig->format = mFormat;
6727 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6728 dstConfig->format = srcConfig->format;
6729 }
6730 } else {
6731 dstConfig->format = AUDIO_FORMAT_INVALID;
6732 }
6733 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6734 dstConfig->gain = mGain;
6735 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6736 dstConfig->gain = srcConfig->gain;
6737 }
6738 } else {
6739 dstConfig->gain.index = -1;
6740 }
6741 if (dstConfig->gain.index != -1) {
6742 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6743 } else {
6744 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6745 }
6746}
6747
Eric Laurent1c333e22014-05-20 10:48:17 -07006748// --- IOProfile class implementation
6749
Eric Laurent1afeecb2014-05-14 08:52:28 -07006750AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006751 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006752 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006753{
6754}
6755
Eric Laurente0720872014-03-11 09:30:41 -07006756AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006757{
6758}
6759
6760// checks if the IO profile is compatible with specified parameters.
6761// Sampling rate, format and channel mask must be specified in order to
6762// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006763bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006764 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006765 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006766 audio_format_t format,
6767 audio_channel_mask_t channelMask,
Eric Laurent5dbe4712014-09-19 19:04:57 -07006768 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07006769{
Glenn Kastencbd48022014-07-24 13:46:44 -07006770 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6771 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6772 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006773
Glenn Kastencbd48022014-07-24 13:46:44 -07006774 if ((mSupportedDevices.types() & device) != device) {
6775 return false;
6776 }
6777
6778 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006779 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006780 }
6781 uint32_t myUpdatedSamplingRate = samplingRate;
6782 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006783 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006784 }
6785 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6786 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006787 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006788 }
6789
6790 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6791 return false;
6792 }
6793
6794 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6795 checkExactChannelMask(channelMask) != NO_ERROR)) {
6796 return false;
6797 }
6798 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6799 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6800 return false;
6801 }
6802
6803 if (isPlaybackThread && (mFlags & flags) != flags) {
6804 return false;
6805 }
6806 // The only input flag that is allowed to be different is the fast flag.
6807 // An existing fast stream is compatible with a normal track request.
6808 // An existing normal stream is compatible with a fast track request,
6809 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07006810 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07006811 ~AUDIO_INPUT_FLAG_FAST)) {
6812 return false;
6813 }
6814
6815 if (updatedSamplingRate != NULL) {
6816 *updatedSamplingRate = myUpdatedSamplingRate;
6817 }
6818 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006819}
6820
Eric Laurente0720872014-03-11 09:30:41 -07006821void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006822{
6823 const size_t SIZE = 256;
6824 char buffer[SIZE];
6825 String8 result;
6826
Eric Laurent1afeecb2014-05-14 08:52:28 -07006827 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006828
Eric Laurente552edb2014-03-10 17:42:56 -07006829 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6830 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006831 snprintf(buffer, SIZE, " - devices:\n");
6832 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006833 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006834 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6835 mSupportedDevices[i]->dump(fd, 6, i);
6836 }
Eric Laurente552edb2014-03-10 17:42:56 -07006837}
6838
Eric Laurentd4692962014-05-05 18:13:44 -07006839void AudioPolicyManager::IOProfile::log()
6840{
6841 const size_t SIZE = 256;
6842 char buffer[SIZE];
6843 String8 result;
6844
6845 ALOGV(" - sampling rates: ");
6846 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6847 ALOGV(" %d", mSamplingRates[i]);
6848 }
6849
6850 ALOGV(" - channel masks: ");
6851 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6852 ALOGV(" 0x%04x", mChannelMasks[i]);
6853 }
6854
6855 ALOGV(" - formats: ");
6856 for (size_t i = 0; i < mFormats.size(); i++) {
6857 ALOGV(" 0x%08x", mFormats[i]);
6858 }
6859
6860 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6861 ALOGV(" - flags: 0x%04x\n", mFlags);
6862}
6863
6864
Eric Laurent3a4311c2014-03-17 12:00:47 -07006865// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006866
Eric Laurent1f2f2232014-06-02 12:01:23 -07006867
6868AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6869 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6870 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6871 AUDIO_PORT_ROLE_SOURCE,
6872 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006873 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006874{
Eric Laurenta121f902014-06-03 13:32:54 -07006875 if (mGains.size() > 0) {
6876 mGains[0]->getDefaultConfig(&mGain);
6877 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006878}
6879
Eric Laurent3a4311c2014-03-17 12:00:47 -07006880bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006881{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006882 // Devices are considered equal if they:
6883 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6884 // - have the same address or one device does not specify the address
6885 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006886 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006887 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006888 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006889 mChannelMask == other->mChannelMask);
6890}
6891
6892void AudioPolicyManager::DeviceVector::refreshTypes()
6893{
Eric Laurent1c333e22014-05-20 10:48:17 -07006894 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006895 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006896 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006897 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006898 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006899}
6900
6901ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6902{
6903 for(size_t i = 0; i < size(); i++) {
6904 if (item->equals(itemAt(i))) {
6905 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006906 }
6907 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006908 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006909}
6910
Eric Laurent3a4311c2014-03-17 12:00:47 -07006911ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006912{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006913 ssize_t ret = indexOf(item);
6914
6915 if (ret < 0) {
6916 ret = SortedVector::add(item);
6917 if (ret >= 0) {
6918 refreshTypes();
6919 }
6920 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006921 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006922 ret = -1;
6923 }
6924 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006925}
6926
Eric Laurent3a4311c2014-03-17 12:00:47 -07006927ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6928{
6929 size_t i;
6930 ssize_t ret = indexOf(item);
6931
6932 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006933 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006934 } else {
6935 ret = SortedVector::removeAt(ret);
6936 if (ret >= 0) {
6937 refreshTypes();
6938 }
6939 }
6940 return ret;
6941}
6942
6943void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6944{
6945 DeviceVector deviceList;
6946
6947 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6948 types &= ~role_bit;
6949
6950 while (types) {
6951 uint32_t i = 31 - __builtin_clz(types);
6952 uint32_t type = 1 << i;
6953 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006954 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006955 }
6956}
6957
Eric Laurent1afeecb2014-05-14 08:52:28 -07006958void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6959 const DeviceVector& declaredDevices)
6960{
6961 char *devName = strtok(name, "|");
6962 while (devName != NULL) {
6963 if (strlen(devName) != 0) {
6964 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6965 ARRAY_SIZE(sDeviceNameToEnumTable),
6966 devName);
6967 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07006968 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
6969 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
6970 dev->mAddress = String8("0");
6971 }
6972 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006973 } else {
6974 sp<DeviceDescriptor> deviceDesc =
6975 declaredDevices.getDeviceFromName(String8(devName));
6976 if (deviceDesc != 0) {
6977 add(deviceDesc);
6978 }
6979 }
6980 }
6981 devName = strtok(NULL, "|");
6982 }
6983}
6984
Eric Laurent1c333e22014-05-20 10:48:17 -07006985sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6986 audio_devices_t type, String8 address) const
6987{
6988 sp<DeviceDescriptor> device;
6989 for (size_t i = 0; i < size(); i++) {
6990 if (itemAt(i)->mDeviceType == type) {
6991 device = itemAt(i);
6992 if (itemAt(i)->mAddress = address) {
6993 break;
6994 }
6995 }
6996 }
6997 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6998 type, address.string(), device.get());
6999 return device;
7000}
7001
Eric Laurent6a94d692014-05-20 11:18:06 -07007002sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7003 audio_port_handle_t id) const
7004{
7005 sp<DeviceDescriptor> device;
7006 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007007 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007008 if (itemAt(i)->mId == id) {
7009 device = itemAt(i);
7010 break;
7011 }
7012 }
7013 return device;
7014}
7015
Eric Laurent1c333e22014-05-20 10:48:17 -07007016AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7017 audio_devices_t type) const
7018{
7019 DeviceVector devices;
7020 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7021 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7022 devices.add(itemAt(i));
7023 type &= ~itemAt(i)->mDeviceType;
7024 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7025 itemAt(i)->mDeviceType, itemAt(i).get());
7026 }
7027 }
7028 return devices;
7029}
7030
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007031AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7032 audio_devices_t type, String8 address) const
7033{
7034 DeviceVector devices;
7035 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
7036 for (size_t i = 0; i < size(); i++) {
7037 //ALOGV(" at i=%d: device=%x, addr=%s",
7038 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
7039 if (itemAt(i)->mDeviceType == type) {
7040 if (itemAt(i)->mAddress == address) {
7041 //ALOGV(" found matching address %s", address.string());
7042 devices.add(itemAt(i));
7043 }
7044 }
7045 }
7046 return devices;
7047}
7048
Eric Laurent1afeecb2014-05-14 08:52:28 -07007049sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7050 const String8& name) const
7051{
7052 sp<DeviceDescriptor> device;
7053 for (size_t i = 0; i < size(); i++) {
7054 if (itemAt(i)->mName == name) {
7055 device = itemAt(i);
7056 break;
7057 }
7058 }
7059 return device;
7060}
7061
Eric Laurent6a94d692014-05-20 11:18:06 -07007062void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7063 struct audio_port_config *dstConfig,
7064 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007065{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007066 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7067 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007068 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007069 }
7070
7071 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7072
Eric Laurent6a94d692014-05-20 11:18:06 -07007073 dstConfig->id = mId;
7074 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007075 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007076 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007077 dstConfig->ext.device.type = mDeviceType;
7078 dstConfig->ext.device.hw_module = mModule->mHandle;
7079 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007080}
7081
7082void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7083{
Eric Laurent83b88082014-06-20 18:31:16 -07007084 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007085 AudioPort::toAudioPort(port);
7086 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007087 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007088 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007089 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007090 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7091}
7092
Eric Laurent1afeecb2014-05-14 08:52:28 -07007093status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007094{
7095 const size_t SIZE = 256;
7096 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007097 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007098
Eric Laurent1afeecb2014-05-14 08:52:28 -07007099 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7100 result.append(buffer);
7101 if (mId != 0) {
7102 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7103 result.append(buffer);
7104 }
7105 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7106 enumToString(sDeviceNameToEnumTable,
7107 ARRAY_SIZE(sDeviceNameToEnumTable),
7108 mDeviceType));
7109 result.append(buffer);
7110 if (mAddress.size() != 0) {
7111 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7112 result.append(buffer);
7113 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007114 write(fd, result.string(), result.size());
7115 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007116
7117 return NO_ERROR;
7118}
7119
Eric Laurent4d416952014-08-10 14:07:09 -07007120status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7121{
7122 const size_t SIZE = 256;
7123 char buffer[SIZE];
7124 String8 result;
7125
7126
7127 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7128 result.append(buffer);
7129 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7130 result.append(buffer);
7131 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7132 result.append(buffer);
7133 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7134 result.append(buffer);
7135 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7136 result.append(buffer);
7137 for (size_t i = 0; i < mPatch.num_sources; i++) {
7138 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7139 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7140 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7141 ARRAY_SIZE(sDeviceNameToEnumTable),
7142 mPatch.sources[i].ext.device.type));
7143 } else {
7144 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7145 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7146 }
7147 result.append(buffer);
7148 }
7149 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7150 result.append(buffer);
7151 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7152 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7153 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7154 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7155 ARRAY_SIZE(sDeviceNameToEnumTable),
7156 mPatch.sinks[i].ext.device.type));
7157 } else {
7158 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7159 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7160 }
7161 result.append(buffer);
7162 }
7163
7164 write(fd, result.string(), result.size());
7165 return NO_ERROR;
7166}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007167
7168// --- audio_policy.conf file parsing
7169
Eric Laurent5dbe4712014-09-19 19:04:57 -07007170uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007171{
7172 uint32_t flag = 0;
7173
7174 // it is OK to cast name to non const here as we are not going to use it after
7175 // strtok() modifies it
7176 char *flagName = strtok(name, "|");
7177 while (flagName != NULL) {
7178 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007179 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7180 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007181 flagName);
7182 }
7183 flagName = strtok(NULL, "|");
7184 }
7185 //force direct flag if offload flag is set: offloading implies a direct output stream
7186 // and all common behaviors are driven by checking only the direct flag
7187 // this should normally be set appropriately in the policy configuration file
7188 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7189 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7190 }
7191
Eric Laurent5dbe4712014-09-19 19:04:57 -07007192 return flag;
7193}
7194
7195uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7196{
7197 uint32_t flag = 0;
7198
7199 // it is OK to cast name to non const here as we are not going to use it after
7200 // strtok() modifies it
7201 char *flagName = strtok(name, "|");
7202 while (flagName != NULL) {
7203 if (strlen(flagName) != 0) {
7204 flag |= stringToEnum(sInputFlagNameToEnumTable,
7205 ARRAY_SIZE(sInputFlagNameToEnumTable),
7206 flagName);
7207 }
7208 flagName = strtok(NULL, "|");
7209 }
7210 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007211}
7212
Eric Laurente0720872014-03-11 09:30:41 -07007213audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007214{
7215 uint32_t device = 0;
7216
7217 char *devName = strtok(name, "|");
7218 while (devName != NULL) {
7219 if (strlen(devName) != 0) {
7220 device |= stringToEnum(sDeviceNameToEnumTable,
7221 ARRAY_SIZE(sDeviceNameToEnumTable),
7222 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007223 }
Eric Laurente552edb2014-03-10 17:42:56 -07007224 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007225 }
Eric Laurente552edb2014-03-10 17:42:56 -07007226 return device;
7227}
7228
Eric Laurente0720872014-03-11 09:30:41 -07007229void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007230{
Eric Laurente552edb2014-03-10 17:42:56 -07007231 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007232 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007233 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007234
Eric Laurent1afeecb2014-05-14 08:52:28 -07007235 node = config_find(root, DEVICES_TAG);
7236 if (node != NULL) {
7237 node = node->first_child;
7238 while (node) {
7239 ALOGV("loadHwModule() loading device %s", node->name);
7240 status_t tmpStatus = module->loadDevice(node);
7241 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7242 status = tmpStatus;
7243 }
7244 node = node->next;
7245 }
7246 }
7247 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007248 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007249 node = node->first_child;
7250 while (node) {
7251 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007252 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007253 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7254 status = tmpStatus;
7255 }
7256 node = node->next;
7257 }
7258 }
7259 node = config_find(root, INPUTS_TAG);
7260 if (node != NULL) {
7261 node = node->first_child;
7262 while (node) {
7263 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007264 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007265 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7266 status = tmpStatus;
7267 }
7268 node = node->next;
7269 }
7270 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007271 loadGlobalConfig(root, module);
7272
Eric Laurente552edb2014-03-10 17:42:56 -07007273 if (status == NO_ERROR) {
7274 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007275 }
7276}
7277
Eric Laurente0720872014-03-11 09:30:41 -07007278void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007279{
7280 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7281 if (node == NULL) {
7282 return;
7283 }
7284
7285 node = node->first_child;
7286 while (node) {
7287 ALOGV("loadHwModules() loading module %s", node->name);
7288 loadHwModule(node);
7289 node = node->next;
7290 }
7291}
7292
Eric Laurent1f2f2232014-06-02 12:01:23 -07007293void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007294{
7295 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007296
Eric Laurente552edb2014-03-10 17:42:56 -07007297 if (node == NULL) {
7298 return;
7299 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007300 DeviceVector declaredDevices;
7301 if (module != NULL) {
7302 declaredDevices = module->mDeclaredDevices;
7303 }
7304
Eric Laurente552edb2014-03-10 17:42:56 -07007305 node = node->first_child;
7306 while (node) {
7307 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007308 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7309 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007310 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7311 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007312 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007313 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007314 ARRAY_SIZE(sDeviceNameToEnumTable),
7315 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007316 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007317 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007318 } else {
7319 ALOGW("loadGlobalConfig() default device not specified");
7320 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007321 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007322 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007323 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7324 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007325 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007326 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7327 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7328 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007329 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7330 uint32_t major, minor;
7331 sscanf((char *)node->value, "%u.%u", &major, &minor);
7332 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7333 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7334 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007335 }
7336 node = node->next;
7337 }
7338}
7339
Eric Laurente0720872014-03-11 09:30:41 -07007340status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007341{
7342 cnode *root;
7343 char *data;
7344
7345 data = (char *)load_file(path, NULL);
7346 if (data == NULL) {
7347 return -ENODEV;
7348 }
7349 root = config_node("", "");
7350 config_load(root, data);
7351
Eric Laurente552edb2014-03-10 17:42:56 -07007352 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007353 // legacy audio_policy.conf files have one global_configuration section
7354 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007355 config_free(root);
7356 free(root);
7357 free(data);
7358
7359 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7360
7361 return NO_ERROR;
7362}
7363
Eric Laurente0720872014-03-11 09:30:41 -07007364void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007365{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007366 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007367 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007368 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7369 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007370 mAvailableOutputDevices.add(mDefaultOutputDevice);
7371 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007372
7373 module = new HwModule("primary");
7374
Eric Laurent1afeecb2014-05-14 08:52:28 -07007375 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007376 profile->mSamplingRates.add(44100);
7377 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7378 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007379 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007380 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7381 module->mOutputProfiles.add(profile);
7382
Eric Laurent1afeecb2014-05-14 08:52:28 -07007383 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007384 profile->mSamplingRates.add(8000);
7385 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7386 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007387 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007388 module->mInputProfiles.add(profile);
7389
7390 mHwModules.add(module);
7391}
7392
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007393audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7394{
7395 // flags to stream type mapping
7396 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7397 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7398 }
7399 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7400 return AUDIO_STREAM_BLUETOOTH_SCO;
7401 }
7402
7403 // usage to stream type mapping
7404 switch (attr->usage) {
7405 case AUDIO_USAGE_MEDIA:
7406 case AUDIO_USAGE_GAME:
7407 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7408 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7409 return AUDIO_STREAM_MUSIC;
7410 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7411 return AUDIO_STREAM_SYSTEM;
7412 case AUDIO_USAGE_VOICE_COMMUNICATION:
7413 return AUDIO_STREAM_VOICE_CALL;
7414
7415 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7416 return AUDIO_STREAM_DTMF;
7417
7418 case AUDIO_USAGE_ALARM:
7419 return AUDIO_STREAM_ALARM;
7420 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7421 return AUDIO_STREAM_RING;
7422
7423 case AUDIO_USAGE_NOTIFICATION:
7424 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7425 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7426 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7427 case AUDIO_USAGE_NOTIFICATION_EVENT:
7428 return AUDIO_STREAM_NOTIFICATION;
7429
7430 case AUDIO_USAGE_UNKNOWN:
7431 default:
7432 return AUDIO_STREAM_MUSIC;
7433 }
7434}
Eric Laurente552edb2014-03-10 17:42:56 -07007435}; // namespace android