blob: 536987af1001d5dc73d73b14cedc70b8455e27af [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()
29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30// 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);
Eric Laurente552edb2014-03-10 17:42:56 -0700219
Eric Laurent22226012014-08-01 17:00:54 -0700220 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
221 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700222
223 // connect/disconnect only 1 device at a time
224 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
225
Eric Laurente552edb2014-03-10 17:42:56 -0700226 // handle output devices
227 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700228 SortedVector <audio_io_handle_t> outputs;
229
Eric Laurent1afeecb2014-05-14 08:52:28 -0700230 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
231 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700232 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
233
Eric Laurente552edb2014-03-10 17:42:56 -0700234 // save a copy of the opened output descriptors before any output is opened or closed
235 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
236 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700237 switch (state)
238 {
239 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700240 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700241 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700242 ALOGW("setDeviceConnectionState() device already connected: %x", device);
243 return INVALID_OPERATION;
244 }
245 ALOGV("setDeviceConnectionState() connecting device %x", device);
246
Eric Laurente552edb2014-03-10 17:42:56 -0700247 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700248 index = mAvailableOutputDevices.add(devDesc);
249 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700250 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700251 if (module == 0) {
252 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
253 device);
254 mAvailableOutputDevices.remove(devDesc);
255 return INVALID_OPERATION;
256 }
257 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700258 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700259 } else {
260 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700261 }
262
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700263 if (checkOutputsForDevice(devDesc, state, outputs, address) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700264 mAvailableOutputDevices.remove(devDesc);
265 return INVALID_OPERATION;
266 }
267 // outputs should never be empty here
268 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
269 "checkOutputsForDevice() returned no outputs but status OK");
270 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
271 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700272 break;
273 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700274 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700275 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700276 ALOGW("setDeviceConnectionState() device not connected: %x", device);
277 return INVALID_OPERATION;
278 }
279
Paul McLean5c477aa2014-08-20 16:47:57 -0700280 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
281
282 // Set Disconnect to HALs
283 AudioParameter param = AudioParameter(address);
284 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
285 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
286
Eric Laurente552edb2014-03-10 17:42:56 -0700287 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700288 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700289
Jean-Michel Trivif17026d2014-08-10 14:30:48 -0700290 checkOutputsForDevice(devDesc, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700291 } break;
292
293 default:
294 ALOGE("setDeviceConnectionState() invalid state: %x", state);
295 return BAD_VALUE;
296 }
297
Eric Laurent3a4311c2014-03-17 12:00:47 -0700298 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
299 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700300 checkA2dpSuspend();
301 checkOutputForAllStrategies();
302 // outputs must be closed after checkOutputForAllStrategies() is executed
303 if (!outputs.isEmpty()) {
304 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700305 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700306 // close unused outputs after device disconnection or direct outputs that have been
307 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700308 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700309 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
310 (desc->mDirectOpenCount == 0))) {
311 closeOutput(outputs[i]);
312 }
313 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700314 // check again after closing A2DP output to reset mA2dpSuspended if needed
315 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700316 }
317
318 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700319 if (mPhoneState == AUDIO_MODE_IN_CALL) {
320 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
321 updateCallRouting(newDevice);
322 }
Eric Laurente552edb2014-03-10 17:42:56 -0700323 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 audio_io_handle_t output = mOutputs.keyAt(i);
325 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
326 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
327 true /*fromCache*/);
328 // do not force device change on duplicated output because if device is 0, it will
329 // also force a device 0 for the two outputs it is duplicated to which may override
330 // a valid device selection on those outputs.
331 bool force = !mOutputs.valueAt(i)->isDuplicated()
332 && (!deviceDistinguishesOnAddress(device)
333 // always force when disconnecting (a non-duplicated device)
334 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
335 setOutputDevice(output, newDevice, force, 0);
336 }
Eric Laurente552edb2014-03-10 17:42:56 -0700337 }
338
Eric Laurent72aa32f2014-05-30 18:51:48 -0700339 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700340 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700341 } // end if is output device
342
Eric Laurente552edb2014-03-10 17:42:56 -0700343 // handle input devices
344 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700345 SortedVector <audio_io_handle_t> inputs;
346
Eric Laurent1afeecb2014-05-14 08:52:28 -0700347 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
348 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700349 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700350 switch (state)
351 {
352 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700353 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700354 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700355 ALOGW("setDeviceConnectionState() device already connected: %d", device);
356 return INVALID_OPERATION;
357 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700358 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700359 if (module == NULL) {
360 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
361 device);
362 return INVALID_OPERATION;
363 }
Eric Laurentd4692962014-05-05 18:13:44 -0700364 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
365 return INVALID_OPERATION;
366 }
367
Eric Laurent3a4311c2014-03-17 12:00:47 -0700368 index = mAvailableInputDevices.add(devDesc);
369 if (index >= 0) {
370 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700371 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700372 } else {
373 return NO_MEMORY;
374 }
Eric Laurentd4692962014-05-05 18:13:44 -0700375 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700376
377 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700378 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700379 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700380 ALOGW("setDeviceConnectionState() device not connected: %d", device);
381 return INVALID_OPERATION;
382 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700383
384 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
385
386 // Set Disconnect to HALs
387 AudioParameter param = AudioParameter(address);
388 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
389 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
390
Eric Laurentd4692962014-05-05 18:13:44 -0700391 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700392 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700393
Eric Laurentd4692962014-05-05 18:13:44 -0700394 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700395
396 default:
397 ALOGE("setDeviceConnectionState() invalid state: %x", state);
398 return BAD_VALUE;
399 }
400
Eric Laurentd4692962014-05-05 18:13:44 -0700401 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700402
Eric Laurentc2730ba2014-07-20 15:47:07 -0700403 if (mPhoneState == AUDIO_MODE_IN_CALL) {
404 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
405 updateCallRouting(newDevice);
406 }
407
Eric Laurentb52c1522014-05-20 11:27:36 -0700408 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700409 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700410 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700411
412 ALOGW("setDeviceConnectionState() invalid device: %x", device);
413 return BAD_VALUE;
414}
415
Eric Laurente0720872014-03-11 09:30:41 -0700416audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700417 const char *device_address)
418{
Eric Laurent3b73df72014-03-11 09:06:29 -0700419 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700420 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700421 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700422 ssize_t index;
423 DeviceVector *deviceVector;
424
Eric Laurente552edb2014-03-10 17:42:56 -0700425 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700426 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700427 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700428 deviceVector = &mAvailableInputDevices;
429 } else {
430 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
431 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700432 }
433
Eric Laurent3a4311c2014-03-17 12:00:47 -0700434 index = deviceVector->indexOf(devDesc);
435 if (index >= 0) {
436 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
437 } else {
438 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
439 }
Eric Laurente552edb2014-03-10 17:42:56 -0700440}
441
Eric Laurentc2730ba2014-07-20 15:47:07 -0700442void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
443{
444 bool createTxPatch = false;
445 struct audio_patch patch;
446 patch.num_sources = 1;
447 patch.num_sinks = 1;
448 status_t status;
449 audio_patch_handle_t afPatchHandle;
450 DeviceVector deviceList;
451
452 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
453 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
454
455 // release existing RX patch if any
456 if (mCallRxPatch != 0) {
457 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
458 mCallRxPatch.clear();
459 }
460 // release TX patch if any
461 if (mCallTxPatch != 0) {
462 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
463 mCallTxPatch.clear();
464 }
465
466 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
467 // via setOutputDevice() on primary output.
468 // Otherwise, create two audio patches for TX and RX path.
469 if (availablePrimaryOutputDevices() & rxDevice) {
470 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
471 // If the TX device is also on the primary HW module, setOutputDevice() will take care
472 // of it due to legacy implementation. If not, create a patch.
473 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
474 == AUDIO_DEVICE_NONE) {
475 createTxPatch = true;
476 }
477 } else {
478 // create RX path audio patch
479 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
480 ALOG_ASSERT(!deviceList.isEmpty(),
481 "updateCallRouting() selected device not in output device list");
482 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
483 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
484 ALOG_ASSERT(!deviceList.isEmpty(),
485 "updateCallRouting() no telephony RX device");
486 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
487
488 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
489 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
490
491 // request to reuse existing output stream if one is already opened to reach the RX device
492 SortedVector<audio_io_handle_t> outputs =
493 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700494 audio_io_handle_t output = selectOutput(outputs,
495 AUDIO_OUTPUT_FLAG_NONE,
496 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700497 if (output != AUDIO_IO_HANDLE_NONE) {
498 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
499 ALOG_ASSERT(!outputDesc->isDuplicated(),
500 "updateCallRouting() RX device output is duplicated");
501 outputDesc->toAudioPortConfig(&patch.sources[1]);
502 patch.num_sources = 2;
503 }
504
505 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
506 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
507 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
508 status);
509 if (status == NO_ERROR) {
510 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
511 &patch, mUidCached);
512 mCallRxPatch->mAfPatchHandle = afPatchHandle;
513 mCallRxPatch->mUid = mUidCached;
514 }
515 createTxPatch = true;
516 }
517 if (createTxPatch) {
518
519 struct audio_patch patch;
520 patch.num_sources = 1;
521 patch.num_sinks = 1;
522 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
523 ALOG_ASSERT(!deviceList.isEmpty(),
524 "updateCallRouting() selected device not in input device list");
525 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
526 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
527 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
528 ALOG_ASSERT(!deviceList.isEmpty(),
529 "updateCallRouting() no telephony TX device");
530 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
531 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
532
533 SortedVector<audio_io_handle_t> outputs =
534 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700535 audio_io_handle_t output = selectOutput(outputs,
536 AUDIO_OUTPUT_FLAG_NONE,
537 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700538 // request to reuse existing output stream if one is already opened to reach the TX
539 // path output device
540 if (output != AUDIO_IO_HANDLE_NONE) {
541 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
542 ALOG_ASSERT(!outputDesc->isDuplicated(),
543 "updateCallRouting() RX device output is duplicated");
544 outputDesc->toAudioPortConfig(&patch.sources[1]);
545 patch.num_sources = 2;
546 }
547
548 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
549 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
550 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
551 status);
552 if (status == NO_ERROR) {
553 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
554 &patch, mUidCached);
555 mCallTxPatch->mAfPatchHandle = afPatchHandle;
556 mCallTxPatch->mUid = mUidCached;
557 }
558 }
559}
560
Eric Laurente0720872014-03-11 09:30:41 -0700561void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700562{
563 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700564 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700565 ALOGW("setPhoneState() invalid state %d", state);
566 return;
567 }
568
569 if (state == mPhoneState ) {
570 ALOGW("setPhoneState() setting same state %d", state);
571 return;
572 }
573
574 // if leaving call state, handle special case of active streams
575 // pertaining to sonification strategy see handleIncallSonification()
576 if (isInCall()) {
577 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700578 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
579 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700580 }
581 }
582
583 // store previous phone state for management of sonification strategy below
584 int oldState = mPhoneState;
585 mPhoneState = state;
586 bool force = false;
587
588 // are we entering or starting a call
589 if (!isStateInCall(oldState) && isStateInCall(state)) {
590 ALOGV(" Entering call in setPhoneState()");
591 // force routing command to audio hardware when starting a call
592 // even if no device change is needed
593 force = true;
594 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
595 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
596 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
597 }
598 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
599 ALOGV(" Exiting call in setPhoneState()");
600 // force routing command to audio hardware when exiting a call
601 // even if no device change is needed
602 force = true;
603 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
604 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
605 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
606 }
607 } else if (isStateInCall(state) && (state != oldState)) {
608 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
609 // force routing command to audio hardware when switching between telephony and VoIP
610 // even if no device change is needed
611 force = true;
612 }
613
614 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700615 checkA2dpSuspend();
616 checkOutputForAllStrategies();
617 updateDevicesAndOutputs();
618
Eric Laurent1f2f2232014-06-02 12:01:23 -0700619 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700620
Eric Laurente552edb2014-03-10 17:42:56 -0700621 int delayMs = 0;
622 if (isStateInCall(state)) {
623 nsecs_t sysTime = systemTime();
624 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700625 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700626 // mute media and sonification strategies and delay device switch by the largest
627 // latency of any output where either strategy is active.
628 // This avoid sending the ring tone or music tail into the earpiece or headset.
629 if ((desc->isStrategyActive(STRATEGY_MEDIA,
630 SONIFICATION_HEADSET_MUSIC_DELAY,
631 sysTime) ||
632 desc->isStrategyActive(STRATEGY_SONIFICATION,
633 SONIFICATION_HEADSET_MUSIC_DELAY,
634 sysTime)) &&
635 (delayMs < (int)desc->mLatency*2)) {
636 delayMs = desc->mLatency*2;
637 }
638 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
639 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
640 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
641 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
642 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
643 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
644 }
645 }
646
Eric Laurentc2730ba2014-07-20 15:47:07 -0700647 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
648 // the device returned is not necessarily reachable via this output
649 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
650 // force routing command to audio hardware when ending call
651 // even if no device change is needed
652 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
653 rxDevice = hwOutputDesc->device();
654 }
Eric Laurente552edb2014-03-10 17:42:56 -0700655
Eric Laurentc2730ba2014-07-20 15:47:07 -0700656 if (state == AUDIO_MODE_IN_CALL) {
657 updateCallRouting(rxDevice, delayMs);
658 } else if (oldState == AUDIO_MODE_IN_CALL) {
659 if (mCallRxPatch != 0) {
660 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
661 mCallRxPatch.clear();
662 }
663 if (mCallTxPatch != 0) {
664 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
665 mCallTxPatch.clear();
666 }
667 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
668 } else {
669 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
670 }
Eric Laurente552edb2014-03-10 17:42:56 -0700671 // if entering in call state, handle special case of active streams
672 // pertaining to sonification strategy see handleIncallSonification()
673 if (isStateInCall(state)) {
674 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700675 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
676 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700677 }
678 }
679
680 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700681 if (state == AUDIO_MODE_RINGTONE &&
682 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700683 mLimitRingtoneVolume = true;
684 } else {
685 mLimitRingtoneVolume = false;
686 }
687}
688
Eric Laurente0720872014-03-11 09:30:41 -0700689void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700690 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700691{
692 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
693
694 bool forceVolumeReeval = false;
695 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700696 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
697 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
698 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700699 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
700 return;
701 }
702 forceVolumeReeval = true;
703 mForceUse[usage] = config;
704 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700705 case AUDIO_POLICY_FORCE_FOR_MEDIA:
706 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
707 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
708 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
709 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900710 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700711 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
712 return;
713 }
714 mForceUse[usage] = config;
715 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700716 case AUDIO_POLICY_FORCE_FOR_RECORD:
717 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
718 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700719 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
720 return;
721 }
722 mForceUse[usage] = config;
723 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700724 case AUDIO_POLICY_FORCE_FOR_DOCK:
725 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
726 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
727 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
728 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
729 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700730 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
731 }
732 forceVolumeReeval = true;
733 mForceUse[usage] = config;
734 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700735 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
736 if (config != AUDIO_POLICY_FORCE_NONE &&
737 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700738 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
739 }
740 forceVolumeReeval = true;
741 mForceUse[usage] = config;
742 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900743 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
744 if (config != AUDIO_POLICY_FORCE_NONE &&
745 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
746 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
747 }
748 mForceUse[usage] = config;
749 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700750 default:
751 ALOGW("setForceUse() invalid usage %d", usage);
752 break;
753 }
754
755 // check for device and output changes triggered by new force usage
756 checkA2dpSuspend();
757 checkOutputForAllStrategies();
758 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700759 if (mPhoneState == AUDIO_MODE_IN_CALL) {
760 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
761 updateCallRouting(newDevice);
762 }
Eric Laurente552edb2014-03-10 17:42:56 -0700763 for (size_t i = 0; i < mOutputs.size(); i++) {
764 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700765 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700766 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
767 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
768 }
Eric Laurente552edb2014-03-10 17:42:56 -0700769 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
770 applyStreamVolumes(output, newDevice, 0, true);
771 }
772 }
773
774 audio_io_handle_t activeInput = getActiveInput();
775 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700776 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700777 }
778
779}
780
Eric Laurente0720872014-03-11 09:30:41 -0700781audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700782{
783 return mForceUse[usage];
784}
785
Eric Laurente0720872014-03-11 09:30:41 -0700786void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700787{
788 ALOGV("setSystemProperty() property %s, value %s", property, value);
789}
790
791// Find a direct output profile compatible with the parameters passed, even if the input flags do
792// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700793sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700794 audio_devices_t device,
795 uint32_t samplingRate,
796 audio_format_t format,
797 audio_channel_mask_t channelMask,
798 audio_output_flags_t flags)
799{
800 for (size_t i = 0; i < mHwModules.size(); i++) {
801 if (mHwModules[i]->mHandle == 0) {
802 continue;
803 }
804 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700805 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700806 bool found = profile->isCompatibleProfile(device, samplingRate,
807 NULL /*updatedSamplingRate*/, format, channelMask,
808 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
809 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700810 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
811 return profile;
812 }
Eric Laurente552edb2014-03-10 17:42:56 -0700813 }
814 }
815 return 0;
816}
817
Eric Laurente0720872014-03-11 09:30:41 -0700818audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700819 uint32_t samplingRate,
820 audio_format_t format,
821 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700822 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700823 const audio_offload_info_t *offloadInfo)
824{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700825
Eric Laurent3b73df72014-03-11 09:06:29 -0700826 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700827 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
828 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
829 device, stream, samplingRate, format, channelMask, flags);
830
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700831 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
832 offloadInfo);
833}
834
835audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
836 uint32_t samplingRate,
837 audio_format_t format,
838 audio_channel_mask_t channelMask,
839 audio_output_flags_t flags,
840 const audio_offload_info_t *offloadInfo)
841{
842 if (attr == NULL) {
843 ALOGE("getOutputForAttr() called with NULL audio attributes");
844 return 0;
845 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700846 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
847 attr->usage, attr->content_type, attr->tags, attr->flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700848
849 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
850 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
851 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700852
853 if ((attr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
854 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
855 }
856
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700857 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
858 device, samplingRate, format, channelMask, flags);
859
860 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
861 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
862 offloadInfo);
863}
864
865audio_io_handle_t AudioPolicyManager::getOutputForDevice(
866 audio_devices_t device,
867 audio_stream_type_t stream,
868 uint32_t samplingRate,
869 audio_format_t format,
870 audio_channel_mask_t channelMask,
871 audio_output_flags_t flags,
872 const audio_offload_info_t *offloadInfo)
873{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700874 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700875 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700876 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700877
Eric Laurente552edb2014-03-10 17:42:56 -0700878#ifdef AUDIO_POLICY_TEST
879 if (mCurOutput != 0) {
880 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
881 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
882
883 if (mTestOutputs[mCurOutput] == 0) {
884 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700885 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700886 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700887 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700888 outputDesc->mFlags =
889 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700890 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700891 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
892 config.sample_rate = mTestSamplingRate;
893 config.channel_mask = mTestChannels;
894 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700895 if (offloadInfo != NULL) {
896 config.offload_info = *offloadInfo;
897 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700898 status = mpClientInterface->openOutput(0,
899 &mTestOutputs[mCurOutput],
900 &config,
901 &outputDesc->mDevice,
902 String8(""),
903 &outputDesc->mLatency,
904 outputDesc->mFlags);
905 if (status == NO_ERROR) {
906 outputDesc->mSamplingRate = config.sample_rate;
907 outputDesc->mFormat = config.format;
908 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700909 AudioParameter outputCmd = AudioParameter();
910 outputCmd.addInt(String8("set_id"),mCurOutput);
911 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
912 addOutput(mTestOutputs[mCurOutput], outputDesc);
913 }
914 }
915 return mTestOutputs[mCurOutput];
916 }
917#endif //AUDIO_POLICY_TEST
918
919 // open a direct output if required by specified parameters
920 //force direct flag if offload flag is set: offloading implies a direct output stream
921 // and all common behaviors are driven by checking only the direct flag
922 // this should normally be set appropriately in the policy configuration file
923 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700924 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700925 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700926 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
927 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
928 }
Eric Laurente552edb2014-03-10 17:42:56 -0700929
Eric Laurentb732cf52014-09-24 19:08:21 -0700930 sp<IOProfile> profile;
931
932 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700933 // and not explicitly requested
934 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
935 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700936 audio_channel_count_from_out_mask(channelMask) <= 2) {
937 goto non_direct_output;
938 }
939
Eric Laurente552edb2014-03-10 17:42:56 -0700940 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
941 // creating an offloaded track and tearing it down immediately after start when audioflinger
942 // detects there is an active non offloadable effect.
943 // FIXME: We should check the audio session here but we do not have it in this context.
944 // This may prevent offloading in rare situations where effects are left active by apps
945 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700946
Eric Laurente552edb2014-03-10 17:42:56 -0700947 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
948 !isNonOffloadableEffectEnabled()) {
949 profile = getProfileForDirectOutput(device,
950 samplingRate,
951 format,
952 channelMask,
953 (audio_output_flags_t)flags);
954 }
955
Eric Laurent1c333e22014-05-20 10:48:17 -0700956 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700957 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700958
959 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700960 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700961 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
962 outputDesc = desc;
963 // reuse direct output if currently open and configured with same parameters
964 if ((samplingRate == outputDesc->mSamplingRate) &&
965 (format == outputDesc->mFormat) &&
966 (channelMask == outputDesc->mChannelMask)) {
967 outputDesc->mDirectOpenCount++;
968 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
969 return mOutputs.keyAt(i);
970 }
971 }
972 }
973 // close direct output if currently open and configured with different parameters
974 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700975 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700976 }
977 outputDesc = new AudioOutputDescriptor(profile);
978 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700979 outputDesc->mLatency = 0;
980 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700981 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
982 config.sample_rate = samplingRate;
983 config.channel_mask = channelMask;
984 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700985 if (offloadInfo != NULL) {
986 config.offload_info = *offloadInfo;
987 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700988 status = mpClientInterface->openOutput(profile->mModule->mHandle,
989 &output,
990 &config,
991 &outputDesc->mDevice,
992 String8(""),
993 &outputDesc->mLatency,
994 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700995
996 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700997 if (status != NO_ERROR ||
998 (samplingRate != 0 && samplingRate != config.sample_rate) ||
999 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1000 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001001 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1002 "format %d %d, channelMask %04x %04x", output, samplingRate,
1003 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1004 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001005 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001006 mpClientInterface->closeOutput(output);
1007 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001008 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001009 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001010 outputDesc->mSamplingRate = config.sample_rate;
1011 outputDesc->mChannelMask = config.channel_mask;
1012 outputDesc->mFormat = config.format;
1013 outputDesc->mRefCount[stream] = 0;
1014 outputDesc->mStopTime[stream] = 0;
1015 outputDesc->mDirectOpenCount = 1;
1016
Eric Laurente552edb2014-03-10 17:42:56 -07001017 audio_io_handle_t srcOutput = getOutputForEffect();
1018 addOutput(output, outputDesc);
1019 audio_io_handle_t dstOutput = getOutputForEffect();
1020 if (dstOutput == output) {
1021 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1022 }
1023 mPreviousOutputs = mOutputs;
1024 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001025 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001026 return output;
1027 }
1028
Eric Laurentb732cf52014-09-24 19:08:21 -07001029non_direct_output:
1030
Eric Laurente552edb2014-03-10 17:42:56 -07001031 // ignoring channel mask due to downmix capability in mixer
1032
1033 // open a non direct output
1034
1035 // for non direct outputs, only PCM is supported
1036 if (audio_is_linear_pcm(format)) {
1037 // get which output is suitable for the specified stream. The actual
1038 // routing change will happen when startOutput() will be called
1039 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1040
Eric Laurent8838a382014-09-08 16:44:28 -07001041 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1042 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1043 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001044 }
1045 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1046 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1047
1048 ALOGV("getOutput() returns output %d", output);
1049
1050 return output;
1051}
1052
Eric Laurente0720872014-03-11 09:30:41 -07001053audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001054 audio_output_flags_t flags,
1055 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001056{
1057 // select one output among several that provide a path to a particular device or set of
1058 // devices (the list was previously build by getOutputsForDevice()).
1059 // The priority is as follows:
1060 // 1: the output with the highest number of requested policy flags
1061 // 2: the primary output
1062 // 3: the first output in the list
1063
1064 if (outputs.size() == 0) {
1065 return 0;
1066 }
1067 if (outputs.size() == 1) {
1068 return outputs[0];
1069 }
1070
1071 int maxCommonFlags = 0;
1072 audio_io_handle_t outputFlags = 0;
1073 audio_io_handle_t outputPrimary = 0;
1074
1075 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001076 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001077 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001078 // if a valid format is specified, skip output if not compatible
1079 if (format != AUDIO_FORMAT_INVALID) {
1080 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1081 if (format != outputDesc->mFormat) {
1082 continue;
1083 }
1084 } else if (!audio_is_linear_pcm(format)) {
1085 continue;
1086 }
1087 }
1088
Eric Laurent3b73df72014-03-11 09:06:29 -07001089 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001090 if (commonFlags > maxCommonFlags) {
1091 outputFlags = outputs[i];
1092 maxCommonFlags = commonFlags;
1093 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1094 }
1095 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1096 outputPrimary = outputs[i];
1097 }
1098 }
1099 }
1100
1101 if (outputFlags != 0) {
1102 return outputFlags;
1103 }
1104 if (outputPrimary != 0) {
1105 return outputPrimary;
1106 }
1107
1108 return outputs[0];
1109}
1110
Eric Laurente0720872014-03-11 09:30:41 -07001111status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001112 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001113 int session)
1114{
1115 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1116 ssize_t index = mOutputs.indexOfKey(output);
1117 if (index < 0) {
1118 ALOGW("startOutput() unknown output %d", output);
1119 return BAD_VALUE;
1120 }
1121
Eric Laurent1f2f2232014-06-02 12:01:23 -07001122 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001123
1124 // increment usage count for this stream on the requested output:
1125 // NOTE that the usage count is the same for duplicated output and hardware output which is
1126 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1127 outputDesc->changeRefCount(stream, 1);
1128
1129 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001130 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001131 routing_strategy strategy = getStrategy(stream);
1132 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1133 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
1134 uint32_t waitMs = 0;
1135 bool force = false;
1136 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001137 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001138 if (desc != outputDesc) {
1139 // force a device change if any other output is managed by the same hw
1140 // module and has a current device selection that differs from selected device.
1141 // In this case, the audio HAL must receive the new device selection so that it can
1142 // change the device currently selected by the other active output.
1143 if (outputDesc->sharesHwModuleWith(desc) &&
1144 desc->device() != newDevice) {
1145 force = true;
1146 }
1147 // wait for audio on other active outputs to be presented when starting
1148 // a notification so that audio focus effect can propagate.
1149 uint32_t latency = desc->latency();
1150 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1151 waitMs = latency;
1152 }
1153 }
1154 }
1155 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1156
1157 // handle special case for sonification while in call
1158 if (isInCall()) {
1159 handleIncallSonification(stream, true, false);
1160 }
1161
1162 // apply volume rules for current stream and device if necessary
1163 checkAndSetVolume(stream,
1164 mStreams[stream].getVolumeIndex(newDevice),
1165 output,
1166 newDevice);
1167
1168 // update the outputs if starting an output with a stream that can affect notification
1169 // routing
1170 handleNotificationRoutingForStream(stream);
1171 if (waitMs > muteWaitMs) {
1172 usleep((waitMs - muteWaitMs) * 2 * 1000);
1173 }
1174 }
1175 return NO_ERROR;
1176}
1177
1178
Eric Laurente0720872014-03-11 09:30:41 -07001179status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001180 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001181 int session)
1182{
1183 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1184 ssize_t index = mOutputs.indexOfKey(output);
1185 if (index < 0) {
1186 ALOGW("stopOutput() unknown output %d", output);
1187 return BAD_VALUE;
1188 }
1189
Eric Laurent1f2f2232014-06-02 12:01:23 -07001190 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001191
1192 // handle special case for sonification while in call
1193 if (isInCall()) {
1194 handleIncallSonification(stream, false, false);
1195 }
1196
1197 if (outputDesc->mRefCount[stream] > 0) {
1198 // decrement usage count of this stream on the output
1199 outputDesc->changeRefCount(stream, -1);
1200 // store time at which the stream was stopped - see isStreamActive()
1201 if (outputDesc->mRefCount[stream] == 0) {
1202 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001203 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001204 // delay the device switch by twice the latency because stopOutput() is executed when
1205 // the track stop() command is received and at that time the audio track buffer can
1206 // still contain data that needs to be drained. The latency only covers the audio HAL
1207 // and kernel buffers. Also the latency does not always include additional delay in the
1208 // audio path (audio DSP, CODEC ...)
1209 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1210
1211 // force restoring the device selection on other active outputs if it differs from the
1212 // one being selected for this output
1213 for (size_t i = 0; i < mOutputs.size(); i++) {
1214 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001215 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001216 if (curOutput != output &&
1217 desc->isActive() &&
1218 outputDesc->sharesHwModuleWith(desc) &&
1219 (newDevice != desc->device())) {
1220 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001221 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001222 true,
1223 outputDesc->mLatency*2);
1224 }
1225 }
1226 // update the outputs if stopping one with a stream that can affect notification routing
1227 handleNotificationRoutingForStream(stream);
1228 }
1229 return NO_ERROR;
1230 } else {
1231 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1232 return INVALID_OPERATION;
1233 }
1234}
1235
Eric Laurente0720872014-03-11 09:30:41 -07001236void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001237{
1238 ALOGV("releaseOutput() %d", output);
1239 ssize_t index = mOutputs.indexOfKey(output);
1240 if (index < 0) {
1241 ALOGW("releaseOutput() releasing unknown output %d", output);
1242 return;
1243 }
1244
1245#ifdef AUDIO_POLICY_TEST
1246 int testIndex = testOutputIndex(output);
1247 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001248 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001249 if (outputDesc->isActive()) {
1250 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001251 mOutputs.removeItem(output);
1252 mTestOutputs[testIndex] = 0;
1253 }
1254 return;
1255 }
1256#endif //AUDIO_POLICY_TEST
1257
Eric Laurent1f2f2232014-06-02 12:01:23 -07001258 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001259 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001260 if (desc->mDirectOpenCount <= 0) {
1261 ALOGW("releaseOutput() invalid open count %d for output %d",
1262 desc->mDirectOpenCount, output);
1263 return;
1264 }
1265 if (--desc->mDirectOpenCount == 0) {
1266 closeOutput(output);
1267 // If effects where present on the output, audioflinger moved them to the primary
1268 // output by default: move them back to the appropriate output.
1269 audio_io_handle_t dstOutput = getOutputForEffect();
1270 if (dstOutput != mPrimaryOutput) {
1271 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1272 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001273 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001274 }
1275 }
1276}
1277
1278
Eric Laurente0720872014-03-11 09:30:41 -07001279audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001280 uint32_t samplingRate,
1281 audio_format_t format,
1282 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001283 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001284 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001285{
Eric Laurent4dc68062014-07-28 17:26:49 -07001286 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001287 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001288 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001289
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001290 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001291
1292 if (device == AUDIO_DEVICE_NONE) {
1293 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001294 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001295 }
1296
1297 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001298 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001299 case AUDIO_SOURCE_VOICE_UPLINK:
1300 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1301 break;
1302 case AUDIO_SOURCE_VOICE_DOWNLINK:
1303 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1304 break;
1305 case AUDIO_SOURCE_VOICE_CALL:
1306 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1307 break;
1308 default:
1309 break;
1310 }
1311
Eric Laurent5dbe4712014-09-19 19:04:57 -07001312 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1313 bool isSoundTrigger = false;
1314 audio_source_t halInputSource = inputSource;
1315 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1316 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1317 if (index >= 0) {
1318 input = mSoundTriggerSessions.valueFor(session);
1319 isSoundTrigger = true;
1320 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1321 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1322 } else {
1323 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1324 }
1325 }
1326
Eric Laurent1c333e22014-05-20 10:48:17 -07001327 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001328 samplingRate,
1329 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001330 channelMask,
1331 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001332 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001333 //retry without flags
1334 audio_input_flags_t log_flags = flags;
1335 flags = AUDIO_INPUT_FLAG_NONE;
1336 profile = getInputProfile(device,
1337 samplingRate,
1338 format,
1339 channelMask,
1340 flags);
1341 if (profile == 0) {
1342 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1343 "channelMask 0x%X, flags %#x",
1344 device, samplingRate, format, channelMask, log_flags);
1345 return AUDIO_IO_HANDLE_NONE;
1346 }
Eric Laurente552edb2014-03-10 17:42:56 -07001347 }
1348
1349 if (profile->mModule->mHandle == 0) {
1350 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001351 return AUDIO_IO_HANDLE_NONE;
1352 }
1353
1354 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1355 config.sample_rate = samplingRate;
1356 config.channel_mask = channelMask;
1357 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001358
Eric Laurentcf2c0212014-07-25 16:20:43 -07001359 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1360 &input,
1361 &config,
1362 &device,
1363 String8(""),
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001364 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001365 flags);
1366
1367 // only accept input with the exact requested set of parameters
1368 if (status != NO_ERROR ||
1369 (samplingRate != config.sample_rate) ||
1370 (format != config.format) ||
1371 (channelMask != config.channel_mask)) {
1372 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1373 samplingRate, format, channelMask);
1374 if (input != AUDIO_IO_HANDLE_NONE) {
1375 mpClientInterface->closeInput(input);
1376 }
1377 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001378 }
1379
Eric Laurent1f2f2232014-06-02 12:01:23 -07001380 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001381 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001382 inputDesc->mRefCount = 0;
1383 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001384 inputDesc->mSamplingRate = samplingRate;
1385 inputDesc->mFormat = format;
1386 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001387 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001388 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001389 inputDesc->mIsSoundTrigger = isSoundTrigger;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001390
Eric Laurentd4692962014-05-05 18:13:44 -07001391 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001392 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001393 return input;
1394}
1395
Eric Laurent4dc68062014-07-28 17:26:49 -07001396status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1397 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001398{
1399 ALOGV("startInput() input %d", input);
1400 ssize_t index = mInputs.indexOfKey(input);
1401 if (index < 0) {
1402 ALOGW("startInput() unknown input %d", input);
1403 return BAD_VALUE;
1404 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001405 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001406
Eric Laurent4dc68062014-07-28 17:26:49 -07001407 index = inputDesc->mSessions.indexOf(session);
1408 if (index < 0) {
1409 ALOGW("startInput() unknown session %d on input %d", session, input);
1410 return BAD_VALUE;
1411 }
1412
Glenn Kasten74a8e252014-07-24 14:09:55 -07001413 // virtual input devices are compatible with other input devices
1414 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1415
1416 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001417 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001418 if (activeInput != 0 && activeInput != input) {
1419
1420 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1421 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001422 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001423 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001424 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001425 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1426 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001427 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001428 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001429 return INVALID_OPERATION;
1430 }
1431 }
1432 }
1433
Glenn Kasten74a8e252014-07-24 14:09:55 -07001434 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001435 if (activeInputsCount() == 0) {
1436 SoundTrigger::setCaptureState(true);
1437 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001438 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001439
Glenn Kasten74a8e252014-07-24 14:09:55 -07001440 // Automatically enable the remote submix output when input is started.
1441 // For remote submix (a virtual device), we open only one input per capture request.
1442 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1443 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1444 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1445 }
Eric Laurente552edb2014-03-10 17:42:56 -07001446 }
1447
Eric Laurente552edb2014-03-10 17:42:56 -07001448 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1449
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001450 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001451 return NO_ERROR;
1452}
1453
Eric Laurent4dc68062014-07-28 17:26:49 -07001454status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1455 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001456{
1457 ALOGV("stopInput() input %d", input);
1458 ssize_t index = mInputs.indexOfKey(input);
1459 if (index < 0) {
1460 ALOGW("stopInput() unknown input %d", input);
1461 return BAD_VALUE;
1462 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001463 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001464
Eric Laurent4dc68062014-07-28 17:26:49 -07001465 index = inputDesc->mSessions.indexOf(session);
1466 if (index < 0) {
1467 ALOGW("stopInput() unknown session %d on input %d", session, input);
1468 return BAD_VALUE;
1469 }
1470
Eric Laurente552edb2014-03-10 17:42:56 -07001471 if (inputDesc->mRefCount == 0) {
1472 ALOGW("stopInput() input %d already stopped", input);
1473 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001474 }
1475
1476 inputDesc->mRefCount--;
1477 if (inputDesc->mRefCount == 0) {
1478
Eric Laurente552edb2014-03-10 17:42:56 -07001479 // automatically disable the remote submix output when input is stopped
1480 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1481 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001482 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001483 }
1484
Eric Laurent1c333e22014-05-20 10:48:17 -07001485 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001486
1487 if (activeInputsCount() == 0) {
1488 SoundTrigger::setCaptureState(false);
1489 }
Eric Laurente552edb2014-03-10 17:42:56 -07001490 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001491 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001492}
1493
Eric Laurent4dc68062014-07-28 17:26:49 -07001494void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1495 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001496{
1497 ALOGV("releaseInput() %d", input);
1498 ssize_t index = mInputs.indexOfKey(input);
1499 if (index < 0) {
1500 ALOGW("releaseInput() releasing unknown input %d", input);
1501 return;
1502 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001503 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1504 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001505
1506 index = inputDesc->mSessions.indexOf(session);
1507 if (index < 0) {
1508 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1509 return;
1510 }
1511 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001512 if (inputDesc->mOpenRefCount == 0) {
1513 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1514 return;
1515 }
1516 inputDesc->mOpenRefCount--;
1517 if (inputDesc->mOpenRefCount > 0) {
1518 ALOGV("releaseInput() exit > 0");
1519 return;
1520 }
1521
Eric Laurent05b90f82014-08-27 15:32:29 -07001522 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001523 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001524 ALOGV("releaseInput() exit");
1525}
1526
Eric Laurentd4692962014-05-05 18:13:44 -07001527void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001528 bool patchRemoved = false;
1529
Eric Laurentd4692962014-05-05 18:13:44 -07001530 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001531 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1532 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1533 if (patch_index >= 0) {
1534 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1535 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1536 mAudioPatches.removeItemsAt(patch_index);
1537 patchRemoved = true;
1538 }
Eric Laurentd4692962014-05-05 18:13:44 -07001539 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1540 }
1541 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001542 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001543
1544 if (patchRemoved) {
1545 mpClientInterface->onAudioPatchListUpdate();
1546 }
Eric Laurentd4692962014-05-05 18:13:44 -07001547}
1548
Eric Laurente0720872014-03-11 09:30:41 -07001549void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001550 int indexMin,
1551 int indexMax)
1552{
1553 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1554 if (indexMin < 0 || indexMin >= indexMax) {
1555 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1556 return;
1557 }
1558 mStreams[stream].mIndexMin = indexMin;
1559 mStreams[stream].mIndexMax = indexMax;
1560}
1561
Eric Laurente0720872014-03-11 09:30:41 -07001562status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001563 int index,
1564 audio_devices_t device)
1565{
1566
1567 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1568 return BAD_VALUE;
1569 }
1570 if (!audio_is_output_device(device)) {
1571 return BAD_VALUE;
1572 }
1573
1574 // Force max volume if stream cannot be muted
1575 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1576
1577 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1578 stream, device, index);
1579
1580 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1581 // clear all device specific values
1582 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1583 mStreams[stream].mIndexCur.clear();
1584 }
1585 mStreams[stream].mIndexCur.add(device, index);
1586
1587 // compute and apply stream volume on all outputs according to connected device
1588 status_t status = NO_ERROR;
1589 for (size_t i = 0; i < mOutputs.size(); i++) {
1590 audio_devices_t curDevice =
1591 getDeviceForVolume(mOutputs.valueAt(i)->device());
1592 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1593 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1594 if (volStatus != NO_ERROR) {
1595 status = volStatus;
1596 }
1597 }
1598 }
1599 return status;
1600}
1601
Eric Laurente0720872014-03-11 09:30:41 -07001602status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001603 int *index,
1604 audio_devices_t device)
1605{
1606 if (index == NULL) {
1607 return BAD_VALUE;
1608 }
1609 if (!audio_is_output_device(device)) {
1610 return BAD_VALUE;
1611 }
1612 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1613 // the strategy the stream belongs to.
1614 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1615 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1616 }
1617 device = getDeviceForVolume(device);
1618
1619 *index = mStreams[stream].getVolumeIndex(device);
1620 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1621 return NO_ERROR;
1622}
1623
Eric Laurente0720872014-03-11 09:30:41 -07001624audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001625 const SortedVector<audio_io_handle_t>& outputs)
1626{
1627 // select one output among several suitable for global effects.
1628 // The priority is as follows:
1629 // 1: An offloaded output. If the effect ends up not being offloadable,
1630 // AudioFlinger will invalidate the track and the offloaded output
1631 // will be closed causing the effect to be moved to a PCM output.
1632 // 2: A deep buffer output
1633 // 3: the first output in the list
1634
1635 if (outputs.size() == 0) {
1636 return 0;
1637 }
1638
1639 audio_io_handle_t outputOffloaded = 0;
1640 audio_io_handle_t outputDeepBuffer = 0;
1641
1642 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001643 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001644 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001645 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1646 outputOffloaded = outputs[i];
1647 }
1648 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1649 outputDeepBuffer = outputs[i];
1650 }
1651 }
1652
1653 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1654 outputOffloaded, outputDeepBuffer);
1655 if (outputOffloaded != 0) {
1656 return outputOffloaded;
1657 }
1658 if (outputDeepBuffer != 0) {
1659 return outputDeepBuffer;
1660 }
1661
1662 return outputs[0];
1663}
1664
Eric Laurente0720872014-03-11 09:30:41 -07001665audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001666{
1667 // apply simple rule where global effects are attached to the same output as MUSIC streams
1668
Eric Laurent3b73df72014-03-11 09:06:29 -07001669 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001670 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1671 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1672
1673 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1674 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1675 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1676
1677 return output;
1678}
1679
Eric Laurente0720872014-03-11 09:30:41 -07001680status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001681 audio_io_handle_t io,
1682 uint32_t strategy,
1683 int session,
1684 int id)
1685{
1686 ssize_t index = mOutputs.indexOfKey(io);
1687 if (index < 0) {
1688 index = mInputs.indexOfKey(io);
1689 if (index < 0) {
1690 ALOGW("registerEffect() unknown io %d", io);
1691 return INVALID_OPERATION;
1692 }
1693 }
1694
1695 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1696 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1697 desc->name, desc->memoryUsage);
1698 return INVALID_OPERATION;
1699 }
1700 mTotalEffectsMemory += desc->memoryUsage;
1701 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1702 desc->name, io, strategy, session, id);
1703 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1704
Eric Laurent1f2f2232014-06-02 12:01:23 -07001705 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1706 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1707 effectDesc->mIo = io;
1708 effectDesc->mStrategy = (routing_strategy)strategy;
1709 effectDesc->mSession = session;
1710 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001711
Eric Laurent1f2f2232014-06-02 12:01:23 -07001712 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001713
1714 return NO_ERROR;
1715}
1716
Eric Laurente0720872014-03-11 09:30:41 -07001717status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001718{
1719 ssize_t index = mEffects.indexOfKey(id);
1720 if (index < 0) {
1721 ALOGW("unregisterEffect() unknown effect ID %d", id);
1722 return INVALID_OPERATION;
1723 }
1724
Eric Laurent1f2f2232014-06-02 12:01:23 -07001725 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001726
Eric Laurent1f2f2232014-06-02 12:01:23 -07001727 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001728
Eric Laurent1f2f2232014-06-02 12:01:23 -07001729 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001730 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001731 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1732 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001733 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001734 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001735 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001736 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001737
1738 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001739
1740 return NO_ERROR;
1741}
1742
Eric Laurente0720872014-03-11 09:30:41 -07001743status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001744{
1745 ssize_t index = mEffects.indexOfKey(id);
1746 if (index < 0) {
1747 ALOGW("unregisterEffect() unknown effect ID %d", id);
1748 return INVALID_OPERATION;
1749 }
1750
1751 return setEffectEnabled(mEffects.valueAt(index), enabled);
1752}
1753
Eric Laurent1f2f2232014-06-02 12:01:23 -07001754status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001755{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001756 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001757 ALOGV("setEffectEnabled(%s) effect already %s",
1758 enabled?"true":"false", enabled?"enabled":"disabled");
1759 return INVALID_OPERATION;
1760 }
1761
1762 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001763 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001764 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001765 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001766 return INVALID_OPERATION;
1767 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001768 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001769 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1770 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001771 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001772 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001773 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1774 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001775 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001776 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001777 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1778 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001779 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001780 return NO_ERROR;
1781}
1782
Eric Laurente0720872014-03-11 09:30:41 -07001783bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001784{
1785 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001786 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1787 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1788 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001789 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001790 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001791 return true;
1792 }
1793 }
1794 return false;
1795}
1796
Eric Laurente0720872014-03-11 09:30:41 -07001797bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001798{
1799 nsecs_t sysTime = systemTime();
1800 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001801 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001802 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001803 return true;
1804 }
1805 }
1806 return false;
1807}
1808
Eric Laurente0720872014-03-11 09:30:41 -07001809bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001810 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001811{
1812 nsecs_t sysTime = systemTime();
1813 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001814 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001815 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001816 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001817 return true;
1818 }
1819 }
1820 return false;
1821}
1822
Eric Laurente0720872014-03-11 09:30:41 -07001823bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001824{
1825 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001826 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001827 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001828 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001829 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1830 && (inputDescriptor->mRefCount > 0)) {
1831 return true;
1832 }
1833 }
1834 return false;
1835}
1836
1837
Eric Laurente0720872014-03-11 09:30:41 -07001838status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001839{
1840 const size_t SIZE = 256;
1841 char buffer[SIZE];
1842 String8 result;
1843
1844 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1845 result.append(buffer);
1846
1847 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1848 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001849 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1850 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001851 snprintf(buffer, SIZE, " Force use for communications %d\n",
1852 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001853 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001854 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001855 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001856 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001857 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001858 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001859 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001860 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001861 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001862 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1863 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1864 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001865
Eric Laurent3a4311c2014-03-17 12:00:47 -07001866 snprintf(buffer, SIZE, " Available output devices:\n");
1867 result.append(buffer);
1868 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001869 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001870 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001871 }
1872 snprintf(buffer, SIZE, "\n Available input devices:\n");
1873 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001874 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001875 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001876 }
Eric Laurente552edb2014-03-10 17:42:56 -07001877
1878 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1879 write(fd, buffer, strlen(buffer));
1880 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001881 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001882 write(fd, buffer, strlen(buffer));
1883 mHwModules[i]->dump(fd);
1884 }
1885
1886 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1887 write(fd, buffer, strlen(buffer));
1888 for (size_t i = 0; i < mOutputs.size(); i++) {
1889 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1890 write(fd, buffer, strlen(buffer));
1891 mOutputs.valueAt(i)->dump(fd);
1892 }
1893
1894 snprintf(buffer, SIZE, "\nInputs dump:\n");
1895 write(fd, buffer, strlen(buffer));
1896 for (size_t i = 0; i < mInputs.size(); i++) {
1897 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1898 write(fd, buffer, strlen(buffer));
1899 mInputs.valueAt(i)->dump(fd);
1900 }
1901
1902 snprintf(buffer, SIZE, "\nStreams dump:\n");
1903 write(fd, buffer, strlen(buffer));
1904 snprintf(buffer, SIZE,
1905 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1906 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001907 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001908 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001909 write(fd, buffer, strlen(buffer));
1910 mStreams[i].dump(fd);
1911 }
1912
1913 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1914 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1915 write(fd, buffer, strlen(buffer));
1916
1917 snprintf(buffer, SIZE, "Registered effects:\n");
1918 write(fd, buffer, strlen(buffer));
1919 for (size_t i = 0; i < mEffects.size(); i++) {
1920 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1921 write(fd, buffer, strlen(buffer));
1922 mEffects.valueAt(i)->dump(fd);
1923 }
1924
Eric Laurent4d416952014-08-10 14:07:09 -07001925 snprintf(buffer, SIZE, "\nAudio Patches:\n");
1926 write(fd, buffer, strlen(buffer));
1927 for (size_t i = 0; i < mAudioPatches.size(); i++) {
1928 mAudioPatches[i]->dump(fd, 2, i);
1929 }
Eric Laurente552edb2014-03-10 17:42:56 -07001930
1931 return NO_ERROR;
1932}
1933
1934// This function checks for the parameters which can be offloaded.
1935// This can be enhanced depending on the capability of the DSP and policy
1936// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001937bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001938{
1939 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001940 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001941 offloadInfo.sample_rate, offloadInfo.channel_mask,
1942 offloadInfo.format,
1943 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1944 offloadInfo.has_video);
1945
1946 // Check if offload has been disabled
1947 char propValue[PROPERTY_VALUE_MAX];
1948 if (property_get("audio.offload.disable", propValue, "0")) {
1949 if (atoi(propValue) != 0) {
1950 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1951 return false;
1952 }
1953 }
1954
1955 // Check if stream type is music, then only allow offload as of now.
1956 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1957 {
1958 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1959 return false;
1960 }
1961
1962 //TODO: enable audio offloading with video when ready
1963 if (offloadInfo.has_video)
1964 {
1965 ALOGV("isOffloadSupported: has_video == true, returning false");
1966 return false;
1967 }
1968
1969 //If duration is less than minimum value defined in property, return false
1970 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1971 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1972 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1973 return false;
1974 }
1975 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1976 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1977 return false;
1978 }
1979
1980 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1981 // creating an offloaded track and tearing it down immediately after start when audioflinger
1982 // detects there is an active non offloadable effect.
1983 // FIXME: We should check the audio session here but we do not have it in this context.
1984 // This may prevent offloading in rare situations where effects are left active by apps
1985 // in the background.
1986 if (isNonOffloadableEffectEnabled()) {
1987 return false;
1988 }
1989
1990 // See if there is a profile to support this.
1991 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001992 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001993 offloadInfo.sample_rate,
1994 offloadInfo.format,
1995 offloadInfo.channel_mask,
1996 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001997 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1998 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001999}
2000
Eric Laurent6a94d692014-05-20 11:18:06 -07002001status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2002 audio_port_type_t type,
2003 unsigned int *num_ports,
2004 struct audio_port *ports,
2005 unsigned int *generation)
2006{
2007 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2008 generation == NULL) {
2009 return BAD_VALUE;
2010 }
2011 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2012 if (ports == NULL) {
2013 *num_ports = 0;
2014 }
2015
2016 size_t portsWritten = 0;
2017 size_t portsMax = *num_ports;
2018 *num_ports = 0;
2019 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2020 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2021 for (size_t i = 0;
2022 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2023 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2024 }
2025 *num_ports += mAvailableOutputDevices.size();
2026 }
2027 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2028 for (size_t i = 0;
2029 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2030 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2031 }
2032 *num_ports += mAvailableInputDevices.size();
2033 }
2034 }
2035 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2036 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2037 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2038 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2039 }
2040 *num_ports += mInputs.size();
2041 }
2042 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002043 size_t numOutputs = 0;
2044 for (size_t i = 0; i < mOutputs.size(); i++) {
2045 if (!mOutputs[i]->isDuplicated()) {
2046 numOutputs++;
2047 if (portsWritten < portsMax) {
2048 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2049 }
2050 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002051 }
Eric Laurent84c70242014-06-23 08:46:27 -07002052 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002053 }
2054 }
2055 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002056 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002057 return NO_ERROR;
2058}
2059
2060status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2061{
2062 return NO_ERROR;
2063}
2064
Eric Laurent1f2f2232014-06-02 12:01:23 -07002065sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002066 audio_port_handle_t id) const
2067{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002068 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002069 for (size_t i = 0; i < mOutputs.size(); i++) {
2070 outputDesc = mOutputs.valueAt(i);
2071 if (outputDesc->mId == id) {
2072 break;
2073 }
2074 }
2075 return outputDesc;
2076}
2077
Eric Laurent1f2f2232014-06-02 12:01:23 -07002078sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002079 audio_port_handle_t id) const
2080{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002081 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002082 for (size_t i = 0; i < mInputs.size(); i++) {
2083 inputDesc = mInputs.valueAt(i);
2084 if (inputDesc->mId == id) {
2085 break;
2086 }
2087 }
2088 return inputDesc;
2089}
2090
Eric Laurent1f2f2232014-06-02 12:01:23 -07002091sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2092 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002093{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002094 sp <HwModule> module;
2095
Eric Laurent6a94d692014-05-20 11:18:06 -07002096 for (size_t i = 0; i < mHwModules.size(); i++) {
2097 if (mHwModules[i]->mHandle == 0) {
2098 continue;
2099 }
2100 if (audio_is_output_device(device)) {
2101 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2102 {
2103 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2104 return mHwModules[i];
2105 }
2106 }
2107 } else {
2108 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2109 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2110 device & ~AUDIO_DEVICE_BIT_IN) {
2111 return mHwModules[i];
2112 }
2113 }
2114 }
2115 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002116 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002117}
2118
Eric Laurent1f2f2232014-06-02 12:01:23 -07002119sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002120{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002121 sp <HwModule> module;
2122
Eric Laurent1afeecb2014-05-14 08:52:28 -07002123 for (size_t i = 0; i < mHwModules.size(); i++)
2124 {
2125 if (strcmp(mHwModules[i]->mName, name) == 0) {
2126 return mHwModules[i];
2127 }
2128 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002129 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002130}
2131
Eric Laurentc2730ba2014-07-20 15:47:07 -07002132audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2133{
2134 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2135 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2136 return devices & mAvailableOutputDevices.types();
2137}
2138
2139audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2140{
2141 audio_module_handle_t primaryHandle =
2142 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2143 audio_devices_t devices = AUDIO_DEVICE_NONE;
2144 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2145 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2146 devices |= mAvailableInputDevices[i]->mDeviceType;
2147 }
2148 }
2149 return devices;
2150}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002151
Eric Laurent6a94d692014-05-20 11:18:06 -07002152status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2153 audio_patch_handle_t *handle,
2154 uid_t uid)
2155{
2156 ALOGV("createAudioPatch()");
2157
2158 if (handle == NULL || patch == NULL) {
2159 return BAD_VALUE;
2160 }
2161 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2162
Eric Laurent874c42872014-08-08 15:13:39 -07002163 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2164 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2165 return BAD_VALUE;
2166 }
2167 // only one source per audio patch supported for now
2168 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002169 return INVALID_OPERATION;
2170 }
Eric Laurent874c42872014-08-08 15:13:39 -07002171
2172 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002173 return INVALID_OPERATION;
2174 }
Eric Laurent874c42872014-08-08 15:13:39 -07002175 for (size_t i = 0; i < patch->num_sinks; i++) {
2176 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2177 return INVALID_OPERATION;
2178 }
2179 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002180
2181 sp<AudioPatch> patchDesc;
2182 ssize_t index = mAudioPatches.indexOfKey(*handle);
2183
Eric Laurent6a94d692014-05-20 11:18:06 -07002184 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2185 patch->sources[0].role,
2186 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002187#if LOG_NDEBUG == 0
2188 for (size_t i = 0; i < patch->num_sinks; i++) {
2189 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2190 patch->sinks[i].role,
2191 patch->sinks[i].type);
2192 }
2193#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002194
2195 if (index >= 0) {
2196 patchDesc = mAudioPatches.valueAt(index);
2197 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2198 mUidCached, patchDesc->mUid, uid);
2199 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2200 return INVALID_OPERATION;
2201 }
2202 } else {
2203 *handle = 0;
2204 }
2205
2206 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002207 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002208 if (outputDesc == NULL) {
2209 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2210 return BAD_VALUE;
2211 }
Eric Laurent84c70242014-06-23 08:46:27 -07002212 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2213 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002214 if (patchDesc != 0) {
2215 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2216 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2217 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2218 return BAD_VALUE;
2219 }
2220 }
Eric Laurent874c42872014-08-08 15:13:39 -07002221 DeviceVector devices;
2222 for (size_t i = 0; i < patch->num_sinks; i++) {
2223 // Only support mix to devices connection
2224 // TODO add support for mix to mix connection
2225 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2226 ALOGV("createAudioPatch() source mix but sink is not a device");
2227 return INVALID_OPERATION;
2228 }
2229 sp<DeviceDescriptor> devDesc =
2230 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2231 if (devDesc == 0) {
2232 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2233 return BAD_VALUE;
2234 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002235
Eric Laurent874c42872014-08-08 15:13:39 -07002236 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2237 patch->sources[0].sample_rate,
2238 NULL, // updatedSamplingRate
2239 patch->sources[0].format,
2240 patch->sources[0].channel_mask,
2241 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2242 ALOGV("createAudioPatch() profile not supported for device %08x",
2243 devDesc->mDeviceType);
2244 return INVALID_OPERATION;
2245 }
2246 devices.add(devDesc);
2247 }
2248 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002249 return INVALID_OPERATION;
2250 }
Eric Laurent874c42872014-08-08 15:13:39 -07002251
Eric Laurent6a94d692014-05-20 11:18:06 -07002252 // TODO: reconfigure output format and channels here
2253 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002254 devices.types(), outputDesc->mIoHandle);
2255 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002256 index = mAudioPatches.indexOfKey(*handle);
2257 if (index >= 0) {
2258 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2259 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2260 }
2261 patchDesc = mAudioPatches.valueAt(index);
2262 patchDesc->mUid = uid;
2263 ALOGV("createAudioPatch() success");
2264 } else {
2265 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2266 return INVALID_OPERATION;
2267 }
2268 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2269 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2270 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002271 // only one sink supported when connecting an input device to a mix
2272 if (patch->num_sinks > 1) {
2273 return INVALID_OPERATION;
2274 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002275 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002276 if (inputDesc == NULL) {
2277 return BAD_VALUE;
2278 }
2279 if (patchDesc != 0) {
2280 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2281 return BAD_VALUE;
2282 }
2283 }
2284 sp<DeviceDescriptor> devDesc =
2285 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2286 if (devDesc == 0) {
2287 return BAD_VALUE;
2288 }
2289
Eric Laurent84c70242014-06-23 08:46:27 -07002290 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07002291 patch->sinks[0].sample_rate,
2292 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07002293 patch->sinks[0].format,
2294 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002295 // FIXME for the parameter type,
2296 // and the NONE
2297 (audio_output_flags_t)
2298 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002299 return INVALID_OPERATION;
2300 }
2301 // TODO: reconfigure output format and channels here
2302 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002303 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002304 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002305 index = mAudioPatches.indexOfKey(*handle);
2306 if (index >= 0) {
2307 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2308 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2309 }
2310 patchDesc = mAudioPatches.valueAt(index);
2311 patchDesc->mUid = uid;
2312 ALOGV("createAudioPatch() success");
2313 } else {
2314 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2315 return INVALID_OPERATION;
2316 }
2317 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2318 // device to device connection
2319 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002320 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002321 return BAD_VALUE;
2322 }
2323 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002324 sp<DeviceDescriptor> srcDeviceDesc =
2325 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002326 if (srcDeviceDesc == 0) {
2327 return BAD_VALUE;
2328 }
Eric Laurent874c42872014-08-08 15:13:39 -07002329
Eric Laurent6a94d692014-05-20 11:18:06 -07002330 //update source and sink with our own data as the data passed in the patch may
2331 // be incomplete.
2332 struct audio_patch newPatch = *patch;
2333 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002334
Eric Laurent874c42872014-08-08 15:13:39 -07002335 for (size_t i = 0; i < patch->num_sinks; i++) {
2336 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2337 ALOGV("createAudioPatch() source device but one sink is not a device");
2338 return INVALID_OPERATION;
2339 }
2340
2341 sp<DeviceDescriptor> sinkDeviceDesc =
2342 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2343 if (sinkDeviceDesc == 0) {
2344 return BAD_VALUE;
2345 }
2346 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2347
2348 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2349 // only one sink supported when connected devices across HW modules
2350 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002351 return INVALID_OPERATION;
2352 }
Eric Laurent874c42872014-08-08 15:13:39 -07002353 SortedVector<audio_io_handle_t> outputs =
2354 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2355 mOutputs);
2356 // if the sink device is reachable via an opened output stream, request to go via
2357 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002358 audio_io_handle_t output = selectOutput(outputs,
2359 AUDIO_OUTPUT_FLAG_NONE,
2360 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002361 if (output != AUDIO_IO_HANDLE_NONE) {
2362 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2363 if (outputDesc->isDuplicated()) {
2364 return INVALID_OPERATION;
2365 }
2366 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2367 newPatch.num_sources = 2;
2368 }
Eric Laurent83b88082014-06-20 18:31:16 -07002369 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002370 }
2371 // TODO: check from routing capabilities in config file and other conflicting patches
2372
2373 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2374 if (index >= 0) {
2375 afPatchHandle = patchDesc->mAfPatchHandle;
2376 }
2377
2378 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2379 &afPatchHandle,
2380 0);
2381 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2382 status, afPatchHandle);
2383 if (status == NO_ERROR) {
2384 if (index < 0) {
2385 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2386 &newPatch, uid);
2387 addAudioPatch(patchDesc->mHandle, patchDesc);
2388 } else {
2389 patchDesc->mPatch = newPatch;
2390 }
2391 patchDesc->mAfPatchHandle = afPatchHandle;
2392 *handle = patchDesc->mHandle;
2393 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002394 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002395 } else {
2396 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2397 status);
2398 return INVALID_OPERATION;
2399 }
2400 } else {
2401 return BAD_VALUE;
2402 }
2403 } else {
2404 return BAD_VALUE;
2405 }
2406 return NO_ERROR;
2407}
2408
2409status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2410 uid_t uid)
2411{
2412 ALOGV("releaseAudioPatch() patch %d", handle);
2413
2414 ssize_t index = mAudioPatches.indexOfKey(handle);
2415
2416 if (index < 0) {
2417 return BAD_VALUE;
2418 }
2419 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2420 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2421 mUidCached, patchDesc->mUid, uid);
2422 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2423 return INVALID_OPERATION;
2424 }
2425
2426 struct audio_patch *patch = &patchDesc->mPatch;
2427 patchDesc->mUid = mUidCached;
2428 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002429 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002430 if (outputDesc == NULL) {
2431 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2432 return BAD_VALUE;
2433 }
2434
2435 setOutputDevice(outputDesc->mIoHandle,
2436 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2437 true,
2438 0,
2439 NULL);
2440 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2441 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002442 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002443 if (inputDesc == NULL) {
2444 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2445 return BAD_VALUE;
2446 }
2447 setInputDevice(inputDesc->mIoHandle,
2448 getNewInputDevice(inputDesc->mIoHandle),
2449 true,
2450 NULL);
2451 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2452 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2453 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2454 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2455 status, patchDesc->mAfPatchHandle);
2456 removeAudioPatch(patchDesc->mHandle);
2457 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002458 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002459 } else {
2460 return BAD_VALUE;
2461 }
2462 } else {
2463 return BAD_VALUE;
2464 }
2465 return NO_ERROR;
2466}
2467
2468status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2469 struct audio_patch *patches,
2470 unsigned int *generation)
2471{
2472 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2473 generation == NULL) {
2474 return BAD_VALUE;
2475 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002476 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002477 *num_patches, patches, mAudioPatches.size());
2478 if (patches == NULL) {
2479 *num_patches = 0;
2480 }
2481
2482 size_t patchesWritten = 0;
2483 size_t patchesMax = *num_patches;
2484 for (size_t i = 0;
2485 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2486 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2487 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002488 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002489 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2490 }
2491 *num_patches = mAudioPatches.size();
2492
2493 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002494 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002495 return NO_ERROR;
2496}
2497
Eric Laurente1715a42014-05-20 11:30:42 -07002498status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002499{
Eric Laurente1715a42014-05-20 11:30:42 -07002500 ALOGV("setAudioPortConfig()");
2501
2502 if (config == NULL) {
2503 return BAD_VALUE;
2504 }
2505 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2506 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002507 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2508 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002509 }
2510
Eric Laurenta121f902014-06-03 13:32:54 -07002511 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002512 if (config->type == AUDIO_PORT_TYPE_MIX) {
2513 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002514 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002515 if (outputDesc == NULL) {
2516 return BAD_VALUE;
2517 }
Eric Laurent84c70242014-06-23 08:46:27 -07002518 ALOG_ASSERT(!outputDesc->isDuplicated(),
2519 "setAudioPortConfig() called on duplicated output %d",
2520 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002521 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002522 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002523 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002524 if (inputDesc == NULL) {
2525 return BAD_VALUE;
2526 }
Eric Laurenta121f902014-06-03 13:32:54 -07002527 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002528 } else {
2529 return BAD_VALUE;
2530 }
2531 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2532 sp<DeviceDescriptor> deviceDesc;
2533 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2534 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2535 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2536 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2537 } else {
2538 return BAD_VALUE;
2539 }
2540 if (deviceDesc == NULL) {
2541 return BAD_VALUE;
2542 }
Eric Laurenta121f902014-06-03 13:32:54 -07002543 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002544 } else {
2545 return BAD_VALUE;
2546 }
2547
Eric Laurenta121f902014-06-03 13:32:54 -07002548 struct audio_port_config backupConfig;
2549 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2550 if (status == NO_ERROR) {
2551 struct audio_port_config newConfig;
2552 audioPortConfig->toAudioPortConfig(&newConfig, config);
2553 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002554 }
Eric Laurenta121f902014-06-03 13:32:54 -07002555 if (status != NO_ERROR) {
2556 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002557 }
Eric Laurente1715a42014-05-20 11:30:42 -07002558
2559 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002560}
2561
2562void AudioPolicyManager::clearAudioPatches(uid_t uid)
2563{
2564 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2565 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2566 if (patchDesc->mUid == uid) {
2567 // releaseAudioPatch() removes the patch from mAudioPatches
2568 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2569 i--;
2570 }
2571 }
2572 }
2573}
2574
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002575status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2576 audio_io_handle_t *ioHandle,
2577 audio_devices_t *device)
2578{
2579 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2580 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2581 *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2582
2583 mSoundTriggerSessions.add(*session, *ioHandle);
2584
2585 return NO_ERROR;
2586}
2587
2588status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2589{
2590 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2591 if (index < 0) {
2592 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2593 return BAD_VALUE;
2594 }
2595
2596 mSoundTriggerSessions.removeItem(session);
2597 return NO_ERROR;
2598}
2599
Eric Laurent6a94d692014-05-20 11:18:06 -07002600status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2601 const sp<AudioPatch>& patch)
2602{
2603 ssize_t index = mAudioPatches.indexOfKey(handle);
2604
2605 if (index >= 0) {
2606 ALOGW("addAudioPatch() patch %d already in", handle);
2607 return ALREADY_EXISTS;
2608 }
2609 mAudioPatches.add(handle, patch);
2610 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2611 "sink handle %d",
2612 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2613 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2614 return NO_ERROR;
2615}
2616
2617status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2618{
2619 ssize_t index = mAudioPatches.indexOfKey(handle);
2620
2621 if (index < 0) {
2622 ALOGW("removeAudioPatch() patch %d not in", handle);
2623 return ALREADY_EXISTS;
2624 }
2625 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2626 mAudioPatches.valueAt(index)->mAfPatchHandle);
2627 mAudioPatches.removeItemsAt(index);
2628 return NO_ERROR;
2629}
2630
Eric Laurente552edb2014-03-10 17:42:56 -07002631// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002632// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002633// ----------------------------------------------------------------------------
2634
Eric Laurent3a4311c2014-03-17 12:00:47 -07002635uint32_t AudioPolicyManager::nextUniqueId()
2636{
2637 return android_atomic_inc(&mNextUniqueId);
2638}
2639
Eric Laurent6a94d692014-05-20 11:18:06 -07002640uint32_t AudioPolicyManager::nextAudioPortGeneration()
2641{
2642 return android_atomic_inc(&mAudioPortGeneration);
2643}
2644
Eric Laurente0720872014-03-11 09:30:41 -07002645AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002646 :
2647#ifdef AUDIO_POLICY_TEST
2648 Thread(false),
2649#endif //AUDIO_POLICY_TEST
2650 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002651 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002652 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2653 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002654 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002655 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Vineeta Srivastavaf2ab2192014-10-11 21:59:36 +00002656 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002657{
Eric Laurent6a94d692014-05-20 11:18:06 -07002658 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002659 mpClientInterface = clientInterface;
2660
Eric Laurent3b73df72014-03-11 09:06:29 -07002661 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2662 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002663 }
2664
Eric Laurent1afeecb2014-05-14 08:52:28 -07002665 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002666 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2667 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2668 ALOGE("could not load audio policy configuration file, setting defaults");
2669 defaultAudioPolicyConfig();
2670 }
2671 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002672 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002673
2674 // must be done after reading the policy
2675 initializeVolumeCurves();
2676
2677 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002678 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2679 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002680 for (size_t i = 0; i < mHwModules.size(); i++) {
2681 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2682 if (mHwModules[i]->mHandle == 0) {
2683 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2684 continue;
2685 }
2686 // open all output streams needed to access attached devices
2687 // except for direct output streams that are only opened when they are actually
2688 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002689 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002690 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2691 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002692 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002693
Eric Laurent3a4311c2014-03-17 12:00:47 -07002694 if (outProfile->mSupportedDevices.isEmpty()) {
2695 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2696 continue;
2697 }
2698
Eric Laurentd78f1532014-09-16 16:38:20 -07002699 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
2700 continue;
2701 }
Eric Laurent83b88082014-06-20 18:31:16 -07002702 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2703 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2704 profileType = mDefaultOutputDevice->mDeviceType;
2705 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07002706 // chose first device present in mSupportedDevices also part of
2707 // outputDeviceTypes
2708 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2709 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
2710 if ((profileType & outputDeviceTypes) != 0) {
2711 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002712 }
Eric Laurente552edb2014-03-10 17:42:56 -07002713 }
2714 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002715 if ((profileType & outputDeviceTypes) == 0) {
2716 continue;
2717 }
2718 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
2719
2720 outputDesc->mDevice = profileType;
2721 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2722 config.sample_rate = outputDesc->mSamplingRate;
2723 config.channel_mask = outputDesc->mChannelMask;
2724 config.format = outputDesc->mFormat;
2725 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2726 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2727 &output,
2728 &config,
2729 &outputDesc->mDevice,
2730 String8(""),
2731 &outputDesc->mLatency,
2732 outputDesc->mFlags);
2733
2734 if (status != NO_ERROR) {
2735 ALOGW("Cannot open output stream for device %08x on hw module %s",
2736 outputDesc->mDevice,
2737 mHwModules[i]->mName);
2738 } else {
2739 outputDesc->mSamplingRate = config.sample_rate;
2740 outputDesc->mChannelMask = config.channel_mask;
2741 outputDesc->mFormat = config.format;
2742
2743 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
2744 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
2745 ssize_t index =
2746 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2747 // give a valid ID to an attached device once confirmed it is reachable
2748 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2749 mAvailableOutputDevices[index]->mId = nextUniqueId();
2750 mAvailableOutputDevices[index]->mModule = mHwModules[i];
2751 }
2752 }
2753 if (mPrimaryOutput == 0 &&
2754 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2755 mPrimaryOutput = output;
2756 }
2757 addOutput(output, outputDesc);
2758 setOutputDevice(output,
2759 outputDesc->mDevice,
2760 true);
2761 }
Eric Laurente552edb2014-03-10 17:42:56 -07002762 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002763 // open input streams needed to access attached devices to validate
2764 // mAvailableInputDevices list
2765 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2766 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002767 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002768
Eric Laurent3a4311c2014-03-17 12:00:47 -07002769 if (inProfile->mSupportedDevices.isEmpty()) {
2770 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2771 continue;
2772 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002773 // chose first device present in mSupportedDevices also part of
2774 // inputDeviceTypes
2775 audio_devices_t profileType = AUDIO_DEVICE_NONE;
2776 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2777 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
2778 if (profileType & inputDeviceTypes) {
2779 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002780 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002781 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002782 if ((profileType & inputDeviceTypes) == 0) {
2783 continue;
2784 }
2785 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2786
2787 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2788 inputDesc->mDevice = profileType;
2789
2790 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2791 config.sample_rate = inputDesc->mSamplingRate;
2792 config.channel_mask = inputDesc->mChannelMask;
2793 config.format = inputDesc->mFormat;
2794 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2795 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2796 &input,
2797 &config,
2798 &inputDesc->mDevice,
2799 String8(""),
2800 AUDIO_SOURCE_MIC,
2801 AUDIO_INPUT_FLAG_NONE);
2802
2803 if (status == NO_ERROR) {
2804 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
2805 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
2806 ssize_t index =
2807 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2808 // give a valid ID to an attached device once confirmed it is reachable
2809 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2810 mAvailableInputDevices[index]->mId = nextUniqueId();
2811 mAvailableInputDevices[index]->mModule = mHwModules[i];
2812 }
2813 }
2814 mpClientInterface->closeInput(input);
2815 } else {
2816 ALOGW("Cannot open input stream for device %08x on hw module %s",
2817 inputDesc->mDevice,
2818 mHwModules[i]->mName);
2819 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002820 }
2821 }
2822 // make sure all attached devices have been allocated a unique ID
2823 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2824 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002825 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002826 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2827 continue;
2828 }
2829 i++;
2830 }
2831 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2832 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002833 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002834 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2835 continue;
2836 }
2837 i++;
2838 }
2839 // make sure default device is reachable
2840 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002841 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002842 }
Eric Laurente552edb2014-03-10 17:42:56 -07002843
2844 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2845
2846 updateDevicesAndOutputs();
2847
2848#ifdef AUDIO_POLICY_TEST
2849 if (mPrimaryOutput != 0) {
2850 AudioParameter outputCmd = AudioParameter();
2851 outputCmd.addInt(String8("set_id"), 0);
2852 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2853
2854 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2855 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002856 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2857 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002858 mTestLatencyMs = 0;
2859 mCurOutput = 0;
2860 mDirectOutput = false;
2861 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2862 mTestOutputs[i] = 0;
2863 }
2864
2865 const size_t SIZE = 256;
2866 char buffer[SIZE];
2867 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2868 run(buffer, ANDROID_PRIORITY_AUDIO);
2869 }
2870#endif //AUDIO_POLICY_TEST
2871}
2872
Eric Laurente0720872014-03-11 09:30:41 -07002873AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002874{
2875#ifdef AUDIO_POLICY_TEST
2876 exit();
2877#endif //AUDIO_POLICY_TEST
2878 for (size_t i = 0; i < mOutputs.size(); i++) {
2879 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002880 }
2881 for (size_t i = 0; i < mInputs.size(); i++) {
2882 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002883 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002884 mAvailableOutputDevices.clear();
2885 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002886 mOutputs.clear();
2887 mInputs.clear();
2888 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002889}
2890
Eric Laurente0720872014-03-11 09:30:41 -07002891status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002892{
2893 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2894}
2895
2896#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002897bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002898{
2899 ALOGV("entering threadLoop()");
2900 while (!exitPending())
2901 {
2902 String8 command;
2903 int valueInt;
2904 String8 value;
2905
2906 Mutex::Autolock _l(mLock);
2907 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2908
2909 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2910 AudioParameter param = AudioParameter(command);
2911
2912 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2913 valueInt != 0) {
2914 ALOGV("Test command %s received", command.string());
2915 String8 target;
2916 if (param.get(String8("target"), target) != NO_ERROR) {
2917 target = "Manager";
2918 }
2919 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2920 param.remove(String8("test_cmd_policy_output"));
2921 mCurOutput = valueInt;
2922 }
2923 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2924 param.remove(String8("test_cmd_policy_direct"));
2925 if (value == "false") {
2926 mDirectOutput = false;
2927 } else if (value == "true") {
2928 mDirectOutput = true;
2929 }
2930 }
2931 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2932 param.remove(String8("test_cmd_policy_input"));
2933 mTestInput = valueInt;
2934 }
2935
2936 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2937 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002938 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002939 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002940 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002941 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002942 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002943 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002944 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002945 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002946 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002947 if (target == "Manager") {
2948 mTestFormat = format;
2949 } else if (mTestOutputs[mCurOutput] != 0) {
2950 AudioParameter outputParam = AudioParameter();
2951 outputParam.addInt(String8("format"), format);
2952 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2953 }
2954 }
2955 }
2956 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2957 param.remove(String8("test_cmd_policy_channels"));
2958 int channels = 0;
2959
2960 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002961 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002962 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002963 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002964 }
2965 if (channels != 0) {
2966 if (target == "Manager") {
2967 mTestChannels = channels;
2968 } else if (mTestOutputs[mCurOutput] != 0) {
2969 AudioParameter outputParam = AudioParameter();
2970 outputParam.addInt(String8("channels"), channels);
2971 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2972 }
2973 }
2974 }
2975 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2976 param.remove(String8("test_cmd_policy_sampleRate"));
2977 if (valueInt >= 0 && valueInt <= 96000) {
2978 int samplingRate = valueInt;
2979 if (target == "Manager") {
2980 mTestSamplingRate = samplingRate;
2981 } else if (mTestOutputs[mCurOutput] != 0) {
2982 AudioParameter outputParam = AudioParameter();
2983 outputParam.addInt(String8("sampling_rate"), samplingRate);
2984 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2985 }
2986 }
2987 }
2988
2989 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2990 param.remove(String8("test_cmd_policy_reopen"));
2991
Eric Laurent1f2f2232014-06-02 12:01:23 -07002992 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002993 mpClientInterface->closeOutput(mPrimaryOutput);
2994
2995 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2996
Eric Laurente552edb2014-03-10 17:42:56 -07002997 mOutputs.removeItem(mPrimaryOutput);
2998
Eric Laurent1f2f2232014-06-02 12:01:23 -07002999 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003000 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003001 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3002 config.sample_rate = outputDesc->mSamplingRate;
3003 config.channel_mask = outputDesc->mChannelMask;
3004 config.format = outputDesc->mFormat;
3005 status_t status = mpClientInterface->openOutput(moduleHandle,
3006 &mPrimaryOutput,
3007 &config,
3008 &outputDesc->mDevice,
3009 String8(""),
3010 &outputDesc->mLatency,
3011 outputDesc->mFlags);
3012 if (status != NO_ERROR) {
3013 ALOGE("Failed to reopen hardware output stream, "
3014 "samplingRate: %d, format %d, channels %d",
3015 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003016 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003017 outputDesc->mSamplingRate = config.sample_rate;
3018 outputDesc->mChannelMask = config.channel_mask;
3019 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003020 AudioParameter outputCmd = AudioParameter();
3021 outputCmd.addInt(String8("set_id"), 0);
3022 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3023 addOutput(mPrimaryOutput, outputDesc);
3024 }
3025 }
3026
3027
3028 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3029 }
3030 }
3031 return false;
3032}
3033
Eric Laurente0720872014-03-11 09:30:41 -07003034void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003035{
3036 {
3037 AutoMutex _l(mLock);
3038 requestExit();
3039 mWaitWorkCV.signal();
3040 }
3041 requestExitAndWait();
3042}
3043
Eric Laurente0720872014-03-11 09:30:41 -07003044int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003045{
3046 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3047 if (output == mTestOutputs[i]) return i;
3048 }
3049 return 0;
3050}
3051#endif //AUDIO_POLICY_TEST
3052
3053// ---
3054
Eric Laurent1f2f2232014-06-02 12:01:23 -07003055void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003056{
Eric Laurent1c333e22014-05-20 10:48:17 -07003057 outputDesc->mIoHandle = output;
3058 outputDesc->mId = nextUniqueId();
3059 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003060 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003061}
3062
Eric Laurent1f2f2232014-06-02 12:01:23 -07003063void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003064{
Eric Laurent1c333e22014-05-20 10:48:17 -07003065 inputDesc->mIoHandle = input;
3066 inputDesc->mId = nextUniqueId();
3067 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003068 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003069}
Eric Laurente552edb2014-03-10 17:42:56 -07003070
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003071void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
3072 const String8 address /*in*/,
3073 SortedVector<audio_io_handle_t>& outputs /*out*/) {
3074 // look for a match on the given address on the addresses of the outputs:
3075 // find the address by finding the patch that maps to this output
3076 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
3077 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
3078 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
3079 if (patchIdx >= 0) {
3080 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
3081 const int numSinks = patchDesc->mPatch.num_sinks;
3082 for (ssize_t j=0; j < numSinks; j++) {
3083 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
3084 const char* patchAddr =
3085 patchDesc->mPatch.sinks[j].ext.device.address;
3086 if (strncmp(patchAddr,
3087 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003088 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003089 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
3090 outputs.add(desc->mIoHandle);
3091 break;
3092 }
3093 }
3094 }
3095 }
3096}
3097
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003098status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003099 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003100 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003101 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003102{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003103 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003104 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003105 // erase all current sample rates, formats and channel masks
3106 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003107
Eric Laurent3b73df72014-03-11 09:06:29 -07003108 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003109 // first list already open outputs that can be routed to this device
3110 for (size_t i = 0; i < mOutputs.size(); i++) {
3111 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003112 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003113 if (!deviceDistinguishesOnAddress(device)) {
3114 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3115 outputs.add(mOutputs.keyAt(i));
3116 } else {
3117 ALOGV(" checking address match due to device 0x%x", device);
3118 findIoHandlesByAddress(desc, address, outputs);
3119 }
Eric Laurente552edb2014-03-10 17:42:56 -07003120 }
3121 }
3122 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003123 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003124 for (size_t i = 0; i < mHwModules.size(); i++)
3125 {
3126 if (mHwModules[i]->mHandle == 0) {
3127 continue;
3128 }
3129 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3130 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003131 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07003132 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003133 profiles.add(mHwModules[i]->mOutputProfiles[j]);
3134 }
3135 }
3136 }
3137
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003138 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3139
Eric Laurente552edb2014-03-10 17:42:56 -07003140 if (profiles.isEmpty() && outputs.isEmpty()) {
3141 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3142 return BAD_VALUE;
3143 }
3144
3145 // open outputs for matching profiles if needed. Direct outputs are also opened to
3146 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3147 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003148 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003149
3150 // nothing to do if one output is already opened for this profile
3151 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003152 for (j = 0; j < outputs.size(); j++) {
3153 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003154 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003155 // matching profile: save the sample rates, format and channel masks supported
3156 // by the profile in our device descriptor
3157 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003158 break;
3159 }
3160 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003161 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003162 continue;
3163 }
3164
Eric Laurent83b88082014-06-20 18:31:16 -07003165 ALOGV("opening output for device %08x with params %s profile %p",
3166 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003167 desc = new AudioOutputDescriptor(profile);
3168 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003169 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3170 config.sample_rate = desc->mSamplingRate;
3171 config.channel_mask = desc->mChannelMask;
3172 config.format = desc->mFormat;
3173 config.offload_info.sample_rate = desc->mSamplingRate;
3174 config.offload_info.channel_mask = desc->mChannelMask;
3175 config.offload_info.format = desc->mFormat;
3176 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3177 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3178 &output,
3179 &config,
3180 &desc->mDevice,
3181 address,
3182 &desc->mLatency,
3183 desc->mFlags);
3184 if (status == NO_ERROR) {
3185 desc->mSamplingRate = config.sample_rate;
3186 desc->mChannelMask = config.channel_mask;
3187 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003188
Eric Laurentd4692962014-05-05 18:13:44 -07003189 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003190 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003191 char *param = audio_device_address_to_parameter(device, address);
3192 mpClientInterface->setParameters(output, String8(param));
3193 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003194 }
3195
Eric Laurentd4692962014-05-05 18:13:44 -07003196 // Here is where we step through and resolve any "dynamic" fields
3197 String8 reply;
3198 char *value;
3199 if (profile->mSamplingRates[0] == 0) {
3200 reply = mpClientInterface->getParameters(output,
3201 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003202 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003203 reply.string());
3204 value = strpbrk((char *)reply.string(), "=");
3205 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003206 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003207 }
Eric Laurentd4692962014-05-05 18:13:44 -07003208 }
3209 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3210 reply = mpClientInterface->getParameters(output,
3211 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003212 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003213 reply.string());
3214 value = strpbrk((char *)reply.string(), "=");
3215 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003216 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003217 }
Eric Laurentd4692962014-05-05 18:13:44 -07003218 }
3219 if (profile->mChannelMasks[0] == 0) {
3220 reply = mpClientInterface->getParameters(output,
3221 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003222 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003223 reply.string());
3224 value = strpbrk((char *)reply.string(), "=");
3225 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003226 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003227 }
Eric Laurentd4692962014-05-05 18:13:44 -07003228 }
3229 if (((profile->mSamplingRates[0] == 0) &&
3230 (profile->mSamplingRates.size() < 2)) ||
3231 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3232 (profile->mFormats.size() < 2)) ||
3233 ((profile->mChannelMasks[0] == 0) &&
3234 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003235 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003236 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003237 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003238 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3239 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003240 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003241 config.sample_rate = profile->pickSamplingRate();
3242 config.channel_mask = profile->pickChannelMask();
3243 config.format = profile->pickFormat();
3244 config.offload_info.sample_rate = config.sample_rate;
3245 config.offload_info.channel_mask = config.channel_mask;
3246 config.offload_info.format = config.format;
3247 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3248 &output,
3249 &config,
3250 &desc->mDevice,
3251 address,
3252 &desc->mLatency,
3253 desc->mFlags);
3254 if (status == NO_ERROR) {
3255 desc->mSamplingRate = config.sample_rate;
3256 desc->mChannelMask = config.channel_mask;
3257 desc->mFormat = config.format;
3258 } else {
3259 output = AUDIO_IO_HANDLE_NONE;
3260 }
Eric Laurentd4692962014-05-05 18:13:44 -07003261 }
3262
Eric Laurentcf2c0212014-07-25 16:20:43 -07003263 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003264 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07003265 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003266 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003267
Eric Laurentd4692962014-05-05 18:13:44 -07003268 // set initial stream volume for device
3269 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003270
Eric Laurentd4692962014-05-05 18:13:44 -07003271 //TODO: configure audio effect output stage here
3272
3273 // open a duplicating output thread for the new output and the primary output
3274 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3275 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003276 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003277 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003278 sp<AudioOutputDescriptor> dupOutputDesc =
3279 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003280 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3281 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3282 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3283 dupOutputDesc->mFormat = desc->mFormat;
3284 dupOutputDesc->mChannelMask = desc->mChannelMask;
3285 dupOutputDesc->mLatency = desc->mLatency;
3286 addOutput(duplicatedOutput, dupOutputDesc);
3287 applyStreamVolumes(duplicatedOutput, device, 0, true);
3288 } else {
3289 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3290 mPrimaryOutput, output);
3291 mpClientInterface->closeOutput(output);
3292 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003293 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003294 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003295 }
Eric Laurente552edb2014-03-10 17:42:56 -07003296 }
3297 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003298 } else {
3299 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003300 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003301 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003302 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003303 profiles.removeAt(profile_index);
3304 profile_index--;
3305 } else {
3306 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003307 devDesc->importAudioPort(profile);
3308
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003309 if (deviceDistinguishesOnAddress(device)) {
3310 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3311 device, address.string());
3312 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3313 NULL/*patch handle*/, address.string());
3314 }
Eric Laurente552edb2014-03-10 17:42:56 -07003315 ALOGV("checkOutputsForDevice(): adding output %d", output);
3316 }
3317 }
3318
3319 if (profiles.isEmpty()) {
3320 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3321 return BAD_VALUE;
3322 }
Eric Laurentd4692962014-05-05 18:13:44 -07003323 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003324 // check if one opened output is not needed any more after disconnecting one device
3325 for (size_t i = 0; i < mOutputs.size(); i++) {
3326 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003327 if (!desc->isDuplicated()) {
3328 if (!(desc->mProfile->mSupportedDevices.types()
3329 & mAvailableOutputDevices.types())) {
3330 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3331 mOutputs.keyAt(i));
3332 outputs.add(mOutputs.keyAt(i));
3333 } else if (deviceDistinguishesOnAddress(device) &&
3334 // exact match on device
3335 (desc->mProfile->mSupportedDevices.types() == device)) {
3336 findIoHandlesByAddress(desc, address, outputs);
3337 }
Eric Laurente552edb2014-03-10 17:42:56 -07003338 }
3339 }
Eric Laurentd4692962014-05-05 18:13:44 -07003340 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003341 for (size_t i = 0; i < mHwModules.size(); i++)
3342 {
3343 if (mHwModules[i]->mHandle == 0) {
3344 continue;
3345 }
3346 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3347 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003348 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003349 if (profile->mSupportedDevices.types() & device) {
3350 ALOGV("checkOutputsForDevice(): "
3351 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003352 if (profile->mSamplingRates[0] == 0) {
3353 profile->mSamplingRates.clear();
3354 profile->mSamplingRates.add(0);
3355 }
3356 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3357 profile->mFormats.clear();
3358 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3359 }
3360 if (profile->mChannelMasks[0] == 0) {
3361 profile->mChannelMasks.clear();
3362 profile->mChannelMasks.add(0);
3363 }
3364 }
3365 }
3366 }
3367 }
3368 return NO_ERROR;
3369}
3370
Eric Laurentd4692962014-05-05 18:13:44 -07003371status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3372 audio_policy_dev_state_t state,
3373 SortedVector<audio_io_handle_t>& inputs,
3374 const String8 address)
3375{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003376 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003377 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3378 // first list already open inputs that can be routed to this device
3379 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3380 desc = mInputs.valueAt(input_index);
3381 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3382 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3383 inputs.add(mInputs.keyAt(input_index));
3384 }
3385 }
3386
3387 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003388 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003389 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3390 {
3391 if (mHwModules[module_idx]->mHandle == 0) {
3392 continue;
3393 }
3394 for (size_t profile_index = 0;
3395 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3396 profile_index++)
3397 {
3398 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3399 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003400 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003401 profile_index, module_idx);
3402 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3403 }
3404 }
3405 }
3406
3407 if (profiles.isEmpty() && inputs.isEmpty()) {
3408 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3409 return BAD_VALUE;
3410 }
3411
3412 // open inputs for matching profiles if needed. Direct inputs are also opened to
3413 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3414 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3415
Eric Laurent1c333e22014-05-20 10:48:17 -07003416 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003417 // nothing to do if one input is already opened for this profile
3418 size_t input_index;
3419 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3420 desc = mInputs.valueAt(input_index);
3421 if (desc->mProfile == profile) {
3422 break;
3423 }
3424 }
3425 if (input_index != mInputs.size()) {
3426 continue;
3427 }
3428
3429 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3430 desc = new AudioInputDescriptor(profile);
3431 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003432 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3433 config.sample_rate = desc->mSamplingRate;
3434 config.channel_mask = desc->mChannelMask;
3435 config.format = desc->mFormat;
3436 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3437 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3438 &input,
3439 &config,
3440 &desc->mDevice,
3441 address,
3442 AUDIO_SOURCE_MIC,
3443 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003444
Eric Laurentcf2c0212014-07-25 16:20:43 -07003445 if (status == NO_ERROR) {
3446 desc->mSamplingRate = config.sample_rate;
3447 desc->mChannelMask = config.channel_mask;
3448 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003449
Eric Laurentd4692962014-05-05 18:13:44 -07003450 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003451 char *param = audio_device_address_to_parameter(device, address);
3452 mpClientInterface->setParameters(input, String8(param));
3453 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003454 }
3455
3456 // Here is where we step through and resolve any "dynamic" fields
3457 String8 reply;
3458 char *value;
3459 if (profile->mSamplingRates[0] == 0) {
3460 reply = mpClientInterface->getParameters(input,
3461 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3462 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3463 reply.string());
3464 value = strpbrk((char *)reply.string(), "=");
3465 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003466 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003467 }
3468 }
3469 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3470 reply = mpClientInterface->getParameters(input,
3471 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3472 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3473 value = strpbrk((char *)reply.string(), "=");
3474 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003475 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003476 }
3477 }
3478 if (profile->mChannelMasks[0] == 0) {
3479 reply = mpClientInterface->getParameters(input,
3480 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3481 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3482 reply.string());
3483 value = strpbrk((char *)reply.string(), "=");
3484 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003485 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003486 }
3487 }
3488 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3489 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3490 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3491 ALOGW("checkInputsForDevice() direct input missing param");
3492 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003493 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003494 }
3495
3496 if (input != 0) {
3497 addInput(input, desc);
3498 }
3499 } // endif input != 0
3500
Eric Laurentcf2c0212014-07-25 16:20:43 -07003501 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003502 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003503 profiles.removeAt(profile_index);
3504 profile_index--;
3505 } else {
3506 inputs.add(input);
3507 ALOGV("checkInputsForDevice(): adding input %d", input);
3508 }
3509 } // end scan profiles
3510
3511 if (profiles.isEmpty()) {
3512 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3513 return BAD_VALUE;
3514 }
3515 } else {
3516 // Disconnect
3517 // check if one opened input is not needed any more after disconnecting one device
3518 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3519 desc = mInputs.valueAt(input_index);
3520 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3521 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3522 mInputs.keyAt(input_index));
3523 inputs.add(mInputs.keyAt(input_index));
3524 }
3525 }
3526 // Clear any profiles associated with the disconnected device.
3527 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3528 if (mHwModules[module_index]->mHandle == 0) {
3529 continue;
3530 }
3531 for (size_t profile_index = 0;
3532 profile_index < mHwModules[module_index]->mInputProfiles.size();
3533 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003534 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003535 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003536 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003537 profile_index, module_index);
3538 if (profile->mSamplingRates[0] == 0) {
3539 profile->mSamplingRates.clear();
3540 profile->mSamplingRates.add(0);
3541 }
3542 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3543 profile->mFormats.clear();
3544 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3545 }
3546 if (profile->mChannelMasks[0] == 0) {
3547 profile->mChannelMasks.clear();
3548 profile->mChannelMasks.add(0);
3549 }
3550 }
3551 }
3552 }
3553 } // end disconnect
3554
3555 return NO_ERROR;
3556}
3557
3558
Eric Laurente0720872014-03-11 09:30:41 -07003559void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003560{
3561 ALOGV("closeOutput(%d)", output);
3562
Eric Laurent1f2f2232014-06-02 12:01:23 -07003563 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003564 if (outputDesc == NULL) {
3565 ALOGW("closeOutput() unknown output %d", output);
3566 return;
3567 }
3568
3569 // look for duplicated outputs connected to the output being removed.
3570 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003571 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003572 if (dupOutputDesc->isDuplicated() &&
3573 (dupOutputDesc->mOutput1 == outputDesc ||
3574 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003575 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003576 if (dupOutputDesc->mOutput1 == outputDesc) {
3577 outputDesc2 = dupOutputDesc->mOutput2;
3578 } else {
3579 outputDesc2 = dupOutputDesc->mOutput1;
3580 }
3581 // As all active tracks on duplicated output will be deleted,
3582 // and as they were also referenced on the other output, the reference
3583 // count for their stream type must be adjusted accordingly on
3584 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003585 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003586 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003587 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003588 }
3589 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3590 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3591
3592 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003593 mOutputs.removeItem(duplicatedOutput);
3594 }
3595 }
3596
Eric Laurent05b90f82014-08-27 15:32:29 -07003597 nextAudioPortGeneration();
3598
3599 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3600 if (index >= 0) {
3601 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3602 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3603 mAudioPatches.removeItemsAt(index);
3604 mpClientInterface->onAudioPatchListUpdate();
3605 }
3606
Eric Laurente552edb2014-03-10 17:42:56 -07003607 AudioParameter param;
3608 param.add(String8("closing"), String8("true"));
3609 mpClientInterface->setParameters(output, param.toString());
3610
3611 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003612 mOutputs.removeItem(output);
3613 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003614}
3615
3616void AudioPolicyManager::closeInput(audio_io_handle_t input)
3617{
3618 ALOGV("closeInput(%d)", input);
3619
3620 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3621 if (inputDesc == NULL) {
3622 ALOGW("closeInput() unknown input %d", input);
3623 return;
3624 }
3625
Eric Laurent6a94d692014-05-20 11:18:06 -07003626 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003627
3628 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3629 if (index >= 0) {
3630 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3631 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3632 mAudioPatches.removeItemsAt(index);
3633 mpClientInterface->onAudioPatchListUpdate();
3634 }
3635
3636 mpClientInterface->closeInput(input);
3637 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003638}
3639
Eric Laurente0720872014-03-11 09:30:41 -07003640SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003641 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003642{
3643 SortedVector<audio_io_handle_t> outputs;
3644
3645 ALOGVV("getOutputsForDevice() device %04x", device);
3646 for (size_t i = 0; i < openOutputs.size(); i++) {
3647 ALOGVV("output %d isDuplicated=%d device=%04x",
3648 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3649 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3650 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3651 outputs.add(openOutputs.keyAt(i));
3652 }
3653 }
3654 return outputs;
3655}
3656
Eric Laurente0720872014-03-11 09:30:41 -07003657bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003658 SortedVector<audio_io_handle_t>& outputs2)
3659{
3660 if (outputs1.size() != outputs2.size()) {
3661 return false;
3662 }
3663 for (size_t i = 0; i < outputs1.size(); i++) {
3664 if (outputs1[i] != outputs2[i]) {
3665 return false;
3666 }
3667 }
3668 return true;
3669}
3670
Eric Laurente0720872014-03-11 09:30:41 -07003671void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003672{
3673 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3674 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3675 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3676 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3677
3678 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3679 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3680 strategy, srcOutputs[0], dstOutputs[0]);
3681 // mute strategy while moving tracks from one output to another
3682 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003683 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003684 if (desc->isStrategyActive(strategy)) {
3685 setStrategyMute(strategy, true, srcOutputs[i]);
3686 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3687 }
3688 }
3689
3690 // Move effects associated to this strategy from previous output to new output
3691 if (strategy == STRATEGY_MEDIA) {
3692 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3693 SortedVector<audio_io_handle_t> moved;
3694 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003695 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3696 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3697 effectDesc->mIo != fxOutput) {
3698 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003699 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3700 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003701 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003702 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003703 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003704 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003705 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003706 }
3707 }
3708 }
3709 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003710 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3711 if (getStrategy((audio_stream_type_t)i) == strategy) {
3712 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003713 }
3714 }
3715 }
3716}
3717
Eric Laurente0720872014-03-11 09:30:41 -07003718void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003719{
Jon Eklund966095e2014-09-09 15:39:49 -05003720 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3721 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003722 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05003723 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
3724 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07003725 checkOutputForStrategy(STRATEGY_SONIFICATION);
3726 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3727 checkOutputForStrategy(STRATEGY_MEDIA);
3728 checkOutputForStrategy(STRATEGY_DTMF);
3729}
3730
Eric Laurente0720872014-03-11 09:30:41 -07003731audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003732{
Eric Laurente552edb2014-03-10 17:42:56 -07003733 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003734 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003735 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3736 return mOutputs.keyAt(i);
3737 }
3738 }
3739
3740 return 0;
3741}
3742
Eric Laurente0720872014-03-11 09:30:41 -07003743void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003744{
Eric Laurente552edb2014-03-10 17:42:56 -07003745 audio_io_handle_t a2dpOutput = getA2dpOutput();
3746 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003747 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003748 return;
3749 }
3750
Eric Laurent3a4311c2014-03-17 12:00:47 -07003751 bool isScoConnected =
3752 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003753 // suspend A2DP output if:
3754 // (NOT already suspended) &&
3755 // ((SCO device is connected &&
3756 // (forced usage for communication || for record is SCO))) ||
3757 // (phone state is ringing || in call)
3758 //
3759 // restore A2DP output if:
3760 // (Already suspended) &&
3761 // ((SCO device is NOT connected ||
3762 // (forced usage NOT for communication && NOT for record is SCO))) &&
3763 // (phone state is NOT ringing && NOT in call)
3764 //
3765 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003766 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003767 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3768 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3769 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3770 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003771
3772 mpClientInterface->restoreOutput(a2dpOutput);
3773 mA2dpSuspended = false;
3774 }
3775 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003776 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003777 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3778 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3779 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3780 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003781
3782 mpClientInterface->suspendOutput(a2dpOutput);
3783 mA2dpSuspended = true;
3784 }
3785 }
3786}
3787
Eric Laurent1c333e22014-05-20 10:48:17 -07003788audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003789{
3790 audio_devices_t device = AUDIO_DEVICE_NONE;
3791
Eric Laurent1f2f2232014-06-02 12:01:23 -07003792 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003793
3794 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3795 if (index >= 0) {
3796 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3797 if (patchDesc->mUid != mUidCached) {
3798 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3799 outputDesc->device(), outputDesc->mPatchHandle);
3800 return outputDesc->device();
3801 }
3802 }
3803
Eric Laurente552edb2014-03-10 17:42:56 -07003804 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05003805 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003806 // use device for strategy enforced audible
3807 // 2: we are in call or the strategy phone is active on the output:
3808 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05003809 // 3: the strategy for enforced audible is active but not enforced on the output:
3810 // use the device for strategy enforced audible
3811 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003812 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003813 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003814 // use device for strategy "respectful" sonification
Jon Eklund966095e2014-09-09 15:39:49 -05003815 // 6: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003816 // use device for strategy media
Jon Eklund966095e2014-09-09 15:39:49 -05003817 // 7: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07003818 // use device for strategy DTMF
Jon Eklund966095e2014-09-09 15:39:49 -05003819 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
3820 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07003821 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3822 } else if (isInCall() ||
3823 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3824 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05003825 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3826 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07003827 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3828 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3829 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3830 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3831 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3832 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3833 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3834 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3835 }
3836
Eric Laurent1c333e22014-05-20 10:48:17 -07003837 ALOGV("getNewOutputDevice() selected device %x", device);
3838 return device;
3839}
3840
3841audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3842{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003843 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003844
3845 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3846 if (index >= 0) {
3847 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3848 if (patchDesc->mUid != mUidCached) {
3849 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3850 inputDesc->mDevice, inputDesc->mPatchHandle);
3851 return inputDesc->mDevice;
3852 }
3853 }
3854
Eric Laurent1c333e22014-05-20 10:48:17 -07003855 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3856
3857 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003858 return device;
3859}
3860
Eric Laurente0720872014-03-11 09:30:41 -07003861uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003862 return (uint32_t)getStrategy(stream);
3863}
3864
Eric Laurente0720872014-03-11 09:30:41 -07003865audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003866 // By checking the range of stream before calling getStrategy, we avoid
3867 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3868 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003869 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003870 return AUDIO_DEVICE_NONE;
3871 }
3872 audio_devices_t devices;
3873 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3874 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3875 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3876 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003877 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003878 if (outputDesc->isStrategyActive(strategy)) {
3879 devices = outputDesc->device();
3880 break;
3881 }
Eric Laurente552edb2014-03-10 17:42:56 -07003882 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05003883
3884 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
3885 and doesn't really need to.*/
3886 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
3887 devices |= AUDIO_DEVICE_OUT_SPEAKER;
3888 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
3889 }
3890
Eric Laurente552edb2014-03-10 17:42:56 -07003891 return devices;
3892}
3893
Eric Laurente0720872014-03-11 09:30:41 -07003894AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003895 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003896 // stream to strategy mapping
3897 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003898 case AUDIO_STREAM_VOICE_CALL:
3899 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003900 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003901 case AUDIO_STREAM_RING:
3902 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003903 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003904 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003905 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003906 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003907 return STRATEGY_DTMF;
3908 default:
3909 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003910 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003911 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3912 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003913 case AUDIO_STREAM_TTS:
3914 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003915 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003916 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003917 return STRATEGY_ENFORCED_AUDIBLE;
3918 }
3919}
3920
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003921uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3922 // flags to strategy mapping
3923 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3924 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3925 }
3926
3927 // usage to strategy mapping
3928 switch (attr->usage) {
3929 case AUDIO_USAGE_MEDIA:
3930 case AUDIO_USAGE_GAME:
3931 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3932 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3933 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3934 return (uint32_t) STRATEGY_MEDIA;
3935
3936 case AUDIO_USAGE_VOICE_COMMUNICATION:
3937 return (uint32_t) STRATEGY_PHONE;
3938
3939 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3940 return (uint32_t) STRATEGY_DTMF;
3941
3942 case AUDIO_USAGE_ALARM:
3943 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3944 return (uint32_t) STRATEGY_SONIFICATION;
3945
3946 case AUDIO_USAGE_NOTIFICATION:
3947 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3948 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3949 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3950 case AUDIO_USAGE_NOTIFICATION_EVENT:
3951 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3952
3953 case AUDIO_USAGE_UNKNOWN:
3954 default:
3955 return (uint32_t) STRATEGY_MEDIA;
3956 }
3957}
3958
Eric Laurente0720872014-03-11 09:30:41 -07003959void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003960 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003961 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003962 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3963 updateDevicesAndOutputs();
3964 break;
3965 default:
3966 break;
3967 }
3968}
3969
Eric Laurente0720872014-03-11 09:30:41 -07003970audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003971 bool fromCache)
3972{
3973 uint32_t device = AUDIO_DEVICE_NONE;
3974
3975 if (fromCache) {
3976 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3977 strategy, mDeviceForStrategy[strategy]);
3978 return mDeviceForStrategy[strategy];
3979 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003980 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003981 switch (strategy) {
3982
3983 case STRATEGY_SONIFICATION_RESPECTFUL:
3984 if (isInCall()) {
3985 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003986 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003987 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3988 // while media is playing on a remote device, use the the sonification behavior.
3989 // Note that we test this usecase before testing if media is playing because
3990 // the isStreamActive() method only informs about the activity of a stream, not
3991 // if it's for local playback. Note also that we use the same delay between both tests
3992 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05003993 //user "safe" speaker if available instead of normal speaker to avoid triggering
3994 //other acoustic safety mechanisms for notification
3995 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
3996 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003997 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003998 // while media is playing (or has recently played), use the same device
3999 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4000 } else {
4001 // when media is not playing anymore, fall back on the sonification behavior
4002 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004003 //user "safe" speaker if available instead of normal speaker to avoid triggering
4004 //other acoustic safety mechanisms for notification
4005 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4006 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004007 }
4008
4009 break;
4010
4011 case STRATEGY_DTMF:
4012 if (!isInCall()) {
4013 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4014 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4015 break;
4016 }
4017 // when in call, DTMF and PHONE strategies follow the same rules
4018 // FALL THROUGH
4019
4020 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004021 // Force use of only devices on primary output if:
4022 // - in call AND
4023 // - cannot route from voice call RX OR
4024 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4025 if (mPhoneState == AUDIO_MODE_IN_CALL) {
4026 audio_devices_t txDevice = getDeviceForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4027 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4028 if (((mAvailableInputDevices.types() &
4029 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4030 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004031 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004032 AUDIO_DEVICE_API_VERSION_3_0))) {
4033 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4034 }
4035 }
Eric Laurente552edb2014-03-10 17:42:56 -07004036 // for phone strategy, we first consider the forced use and then the available devices by order
4037 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004038 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4039 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004040 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004041 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004042 if (device) break;
4043 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004044 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004045 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004046 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004047 if (device) break;
4048 // if SCO device is requested but no SCO device is available, fall back to default case
4049 // FALL THROUGH
4050
4051 default: // FORCE_NONE
4052 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004053 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004054 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004055 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004056 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004057 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004058 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004059 if (device) break;
4060 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004061 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004062 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004063 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004064 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004065 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4066 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004067 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004068 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004069 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004070 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004071 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004072 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004073 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004074 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004075 if (device) break;
4076 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004077 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004078 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004079 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004080 if (device == AUDIO_DEVICE_NONE) {
4081 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4082 }
4083 break;
4084
Eric Laurent3b73df72014-03-11 09:06:29 -07004085 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004086 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4087 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004088 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004089 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004090 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004091 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004092 if (device) break;
4093 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004094 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004095 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004096 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004097 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004098 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004099 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004100 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004101 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004102 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004103 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004104 if (device) break;
4105 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004106 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4107 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004108 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004109 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004110 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004111 if (device == AUDIO_DEVICE_NONE) {
4112 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4113 }
4114 break;
4115 }
4116 break;
4117
4118 case STRATEGY_SONIFICATION:
4119
4120 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4121 // handleIncallSonification().
4122 if (isInCall()) {
4123 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4124 break;
4125 }
4126 // FALL THROUGH
4127
4128 case STRATEGY_ENFORCED_AUDIBLE:
4129 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4130 // except:
4131 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4132 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4133
4134 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004135 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004136 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004137 if (device == AUDIO_DEVICE_NONE) {
4138 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4139 }
4140 }
4141 // The second device used for sonification is the same as the device used by media strategy
4142 // FALL THROUGH
4143
4144 case STRATEGY_MEDIA: {
4145 uint32_t device2 = AUDIO_DEVICE_NONE;
4146 if (strategy != STRATEGY_SONIFICATION) {
4147 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004148 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07004149 }
4150 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004151 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004152 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004153 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004154 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004155 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004156 }
4157 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004158 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004159 }
4160 }
4161 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004162 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004163 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004164 if ((device2 == AUDIO_DEVICE_NONE)) {
4165 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4166 }
Eric Laurente552edb2014-03-10 17:42:56 -07004167 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004168 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004169 }
4170 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004171 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004172 }
4173 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004174 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004175 }
4176 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004177 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004178 }
4179 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4180 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004181 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004182 }
4183 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004184 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004185 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004186 }
4187 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004188 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004189 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004190 int device3 = AUDIO_DEVICE_NONE;
4191 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004192 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004193 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4194 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004195 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004196 }
Eric Laurente552edb2014-03-10 17:42:56 -07004197
Jungshik Jang839e4f32014-06-26 17:23:40 +09004198 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004199 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4200 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4201 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004202
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004203 // If hdmi system audio mode is on, remove speaker out of output list.
4204 if ((strategy == STRATEGY_MEDIA) &&
4205 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4206 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4207 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4208 }
4209
Eric Laurente552edb2014-03-10 17:42:56 -07004210 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004211 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004212 if (device == AUDIO_DEVICE_NONE) {
4213 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4214 }
4215 } break;
4216
4217 default:
4218 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4219 break;
4220 }
4221
4222 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4223 return device;
4224}
4225
Eric Laurente0720872014-03-11 09:30:41 -07004226void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004227{
4228 for (int i = 0; i < NUM_STRATEGIES; i++) {
4229 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4230 }
4231 mPreviousOutputs = mOutputs;
4232}
4233
Eric Laurent1f2f2232014-06-02 12:01:23 -07004234uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004235 audio_devices_t prevDevice,
4236 uint32_t delayMs)
4237{
4238 // mute/unmute strategies using an incompatible device combination
4239 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4240 // if unmuting, unmute only after the specified delay
4241 if (outputDesc->isDuplicated()) {
4242 return 0;
4243 }
4244
4245 uint32_t muteWaitMs = 0;
4246 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004247 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004248
4249 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4250 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4251 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4252 bool doMute = false;
4253
4254 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4255 doMute = true;
4256 outputDesc->mStrategyMutedByDevice[i] = true;
4257 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4258 doMute = true;
4259 outputDesc->mStrategyMutedByDevice[i] = false;
4260 }
Eric Laurent99401132014-05-07 19:48:15 -07004261 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004262 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004263 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004264 // skip output if it does not share any device with current output
4265 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4266 == AUDIO_DEVICE_NONE) {
4267 continue;
4268 }
4269 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4270 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4271 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4272 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4273 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004274 if (mute) {
4275 // FIXME: should not need to double latency if volume could be applied
4276 // immediately by the audioflinger mixer. We must account for the delay
4277 // between now and the next time the audioflinger thread for this output
4278 // will process a buffer (which corresponds to one buffer size,
4279 // usually 1/2 or 1/4 of the latency).
4280 if (muteWaitMs < desc->latency() * 2) {
4281 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004282 }
4283 }
4284 }
4285 }
4286 }
4287 }
4288
Eric Laurent99401132014-05-07 19:48:15 -07004289 // temporary mute output if device selection changes to avoid volume bursts due to
4290 // different per device volumes
4291 if (outputDesc->isActive() && (device != prevDevice)) {
4292 if (muteWaitMs < outputDesc->latency() * 2) {
4293 muteWaitMs = outputDesc->latency() * 2;
4294 }
4295 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4296 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004297 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004298 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004299 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004300 muteWaitMs *2, device);
4301 }
4302 }
4303 }
4304
Eric Laurente552edb2014-03-10 17:42:56 -07004305 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4306 if (muteWaitMs > delayMs) {
4307 muteWaitMs -= delayMs;
4308 usleep(muteWaitMs * 1000);
4309 return muteWaitMs;
4310 }
4311 return 0;
4312}
4313
Eric Laurente0720872014-03-11 09:30:41 -07004314uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004315 audio_devices_t device,
4316 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004317 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004318 audio_patch_handle_t *patchHandle,
4319 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004320{
4321 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004322 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004323 AudioParameter param;
4324 uint32_t muteWaitMs;
4325
4326 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004327 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4328 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004329 return muteWaitMs;
4330 }
4331 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4332 // output profile
4333 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004334 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004335 return 0;
4336 }
4337
4338 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004339 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004340
4341 audio_devices_t prevDevice = outputDesc->mDevice;
4342
4343 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4344
4345 if (device != AUDIO_DEVICE_NONE) {
4346 outputDesc->mDevice = device;
4347 }
4348 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4349
4350 // Do not change the routing if:
4351 // - the requested device is AUDIO_DEVICE_NONE
4352 // - the requested device is the same as current device and force is not specified.
4353 // Doing this check here allows the caller to call setOutputDevice() without conditions
4354 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
4355 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
4356 return muteWaitMs;
4357 }
4358
4359 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004360
Eric Laurente552edb2014-03-10 17:42:56 -07004361 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004362 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004363 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004364 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004365 DeviceVector deviceList = (address == NULL) ?
4366 mAvailableOutputDevices.getDevicesFromType(device)
4367 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004368 if (!deviceList.isEmpty()) {
4369 struct audio_patch patch;
4370 outputDesc->toAudioPortConfig(&patch.sources[0]);
4371 patch.num_sources = 1;
4372 patch.num_sinks = 0;
4373 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4374 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004375 patch.num_sinks++;
4376 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004377 ssize_t index;
4378 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4379 index = mAudioPatches.indexOfKey(*patchHandle);
4380 } else {
4381 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4382 }
4383 sp< AudioPatch> patchDesc;
4384 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4385 if (index >= 0) {
4386 patchDesc = mAudioPatches.valueAt(index);
4387 afPatchHandle = patchDesc->mAfPatchHandle;
4388 }
4389
Eric Laurent1c333e22014-05-20 10:48:17 -07004390 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004391 &afPatchHandle,
4392 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004393 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4394 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004395 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004396 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004397 if (index < 0) {
4398 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4399 &patch, mUidCached);
4400 addAudioPatch(patchDesc->mHandle, patchDesc);
4401 } else {
4402 patchDesc->mPatch = patch;
4403 }
4404 patchDesc->mAfPatchHandle = afPatchHandle;
4405 patchDesc->mUid = mUidCached;
4406 if (patchHandle) {
4407 *patchHandle = patchDesc->mHandle;
4408 }
4409 outputDesc->mPatchHandle = patchDesc->mHandle;
4410 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004411 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004412 }
4413 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004414
4415 // inform all input as well
4416 for (size_t i = 0; i < mInputs.size(); i++) {
4417 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4418 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4419 AudioParameter inputCmd = AudioParameter();
4420 ALOGV("%s: inform input %d of device:%d", __func__,
4421 inputDescriptor->mIoHandle, device);
4422 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4423 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4424 inputCmd.toString(),
4425 delayMs);
4426 }
4427 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004428 }
Eric Laurente552edb2014-03-10 17:42:56 -07004429
4430 // update stream volumes according to new device
4431 applyStreamVolumes(output, device, delayMs);
4432
4433 return muteWaitMs;
4434}
4435
Eric Laurent1c333e22014-05-20 10:48:17 -07004436status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004437 int delayMs,
4438 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004439{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004440 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004441 ssize_t index;
4442 if (patchHandle) {
4443 index = mAudioPatches.indexOfKey(*patchHandle);
4444 } else {
4445 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4446 }
4447 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004448 return INVALID_OPERATION;
4449 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004450 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4451 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004452 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4453 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004454 removeAudioPatch(patchDesc->mHandle);
4455 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004456 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004457 return status;
4458}
4459
4460status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4461 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004462 bool force,
4463 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004464{
4465 status_t status = NO_ERROR;
4466
Eric Laurent1f2f2232014-06-02 12:01:23 -07004467 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004468 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4469 inputDesc->mDevice = device;
4470
4471 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4472 if (!deviceList.isEmpty()) {
4473 struct audio_patch patch;
4474 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004475 // AUDIO_SOURCE_HOTWORD is for internal use only:
4476 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004477 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4478 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004479 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4480 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004481 patch.num_sinks = 1;
4482 //only one input device for now
4483 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004484 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004485 ssize_t index;
4486 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4487 index = mAudioPatches.indexOfKey(*patchHandle);
4488 } else {
4489 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4490 }
4491 sp< AudioPatch> patchDesc;
4492 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4493 if (index >= 0) {
4494 patchDesc = mAudioPatches.valueAt(index);
4495 afPatchHandle = patchDesc->mAfPatchHandle;
4496 }
4497
Eric Laurent1c333e22014-05-20 10:48:17 -07004498 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004499 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004500 0);
4501 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004502 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004503 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004504 if (index < 0) {
4505 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4506 &patch, mUidCached);
4507 addAudioPatch(patchDesc->mHandle, patchDesc);
4508 } else {
4509 patchDesc->mPatch = patch;
4510 }
4511 patchDesc->mAfPatchHandle = afPatchHandle;
4512 patchDesc->mUid = mUidCached;
4513 if (patchHandle) {
4514 *patchHandle = patchDesc->mHandle;
4515 }
4516 inputDesc->mPatchHandle = patchDesc->mHandle;
4517 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004518 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004519 }
4520 }
4521 }
4522 return status;
4523}
4524
Eric Laurent6a94d692014-05-20 11:18:06 -07004525status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4526 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004527{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004528 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004529 ssize_t index;
4530 if (patchHandle) {
4531 index = mAudioPatches.indexOfKey(*patchHandle);
4532 } else {
4533 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4534 }
4535 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004536 return INVALID_OPERATION;
4537 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004538 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4539 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004540 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4541 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004542 removeAudioPatch(patchDesc->mHandle);
4543 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004544 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004545 return status;
4546}
4547
4548sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004549 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004550 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004551 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004552 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004553{
4554 // Choose an input profile based on the requested capture parameters: select the first available
4555 // profile supporting all requested parameters.
4556
4557 for (size_t i = 0; i < mHwModules.size(); i++)
4558 {
4559 if (mHwModules[i]->mHandle == 0) {
4560 continue;
4561 }
4562 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4563 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004564 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004565 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004566 if (profile->isCompatibleProfile(device, samplingRate,
4567 &samplingRate /*updatedSamplingRate*/,
4568 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004569 return profile;
4570 }
4571 }
4572 }
4573 return NULL;
4574}
4575
Eric Laurente0720872014-03-11 09:30:41 -07004576audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004577{
4578 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004579 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4580 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004581 switch (inputSource) {
4582 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004583 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004584 device = AUDIO_DEVICE_IN_VOICE_CALL;
4585 break;
4586 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004587 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004588
4589 case AUDIO_SOURCE_DEFAULT:
4590 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004591 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4592 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004593 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4594 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4595 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4596 device = AUDIO_DEVICE_IN_USB_DEVICE;
4597 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4598 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004599 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004600 break;
4601
4602 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4603 // Allow only use of devices on primary input if in call and HAL does not support routing
4604 // to voice call path.
4605 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4606 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4607 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4608 }
4609
4610 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4611 case AUDIO_POLICY_FORCE_BT_SCO:
4612 // if SCO device is requested but no SCO device is available, fall back to default case
4613 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4614 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4615 break;
4616 }
4617 // FALL THROUGH
4618
4619 default: // FORCE_NONE
4620 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4621 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4622 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4623 device = AUDIO_DEVICE_IN_USB_DEVICE;
4624 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4625 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4626 }
4627 break;
4628
4629 case AUDIO_POLICY_FORCE_SPEAKER:
4630 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4631 device = AUDIO_DEVICE_IN_BACK_MIC;
4632 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4633 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4634 }
4635 break;
4636 }
4637 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004638
Eric Laurente552edb2014-03-10 17:42:56 -07004639 case AUDIO_SOURCE_VOICE_RECOGNITION:
4640 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004641 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004642 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004643 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004644 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004645 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004646 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4647 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004648 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004649 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4650 }
4651 break;
4652 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004653 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004654 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004655 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004656 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4657 }
4658 break;
4659 case AUDIO_SOURCE_VOICE_DOWNLINK:
4660 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004661 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004662 device = AUDIO_DEVICE_IN_VOICE_CALL;
4663 }
4664 break;
4665 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004666 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004667 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4668 }
4669 break;
4670 default:
4671 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4672 break;
4673 }
4674 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4675 return device;
4676}
4677
Eric Laurente0720872014-03-11 09:30:41 -07004678bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004679{
4680 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4681 device &= ~AUDIO_DEVICE_BIT_IN;
4682 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4683 return true;
4684 }
4685 return false;
4686}
4687
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004688bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4689 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4690}
4691
Eric Laurente0720872014-03-11 09:30:41 -07004692audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004693{
4694 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004695 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004696 if ((input_descriptor->mRefCount > 0)
4697 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4698 return mInputs.keyAt(i);
4699 }
4700 }
4701 return 0;
4702}
4703
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004704uint32_t AudioPolicyManager::activeInputsCount() const
4705{
4706 uint32_t count = 0;
4707 for (size_t i = 0; i < mInputs.size(); i++) {
4708 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4709 if (desc->mRefCount > 0) {
4710 return count++;
4711 }
4712 }
4713 return count;
4714}
4715
Eric Laurente552edb2014-03-10 17:42:56 -07004716
Eric Laurente0720872014-03-11 09:30:41 -07004717audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004718{
4719 if (device == AUDIO_DEVICE_NONE) {
4720 // this happens when forcing a route update and no track is active on an output.
4721 // In this case the returned category is not important.
4722 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004723 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004724 // Multiple device selection is either:
4725 // - speaker + one other device: give priority to speaker in this case.
4726 // - one A2DP device + another device: happens with duplicated output. In this case
4727 // retain the device on the A2DP output as the other must not correspond to an active
4728 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004729 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004730 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4731 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004732 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4733 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4734 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4735 device = AUDIO_DEVICE_OUT_AUX_LINE;
4736 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4737 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004738 } else {
4739 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4740 }
4741 }
4742
Jon Eklund11c9fb12014-06-23 14:47:03 -05004743 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4744 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4745 device = AUDIO_DEVICE_OUT_SPEAKER;
4746
Eric Laurent3b73df72014-03-11 09:06:29 -07004747 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004748 "getDeviceForVolume() invalid device combination: %08x",
4749 device);
4750
4751 return device;
4752}
4753
Eric Laurente0720872014-03-11 09:30:41 -07004754AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004755{
4756 switch(getDeviceForVolume(device)) {
4757 case AUDIO_DEVICE_OUT_EARPIECE:
4758 return DEVICE_CATEGORY_EARPIECE;
4759 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4760 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4761 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4762 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4763 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4764 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4765 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004766 case AUDIO_DEVICE_OUT_LINE:
4767 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4768 /*USB? Remote submix?*/
4769 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004770 case AUDIO_DEVICE_OUT_SPEAKER:
4771 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4772 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004773 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4774 case AUDIO_DEVICE_OUT_USB_DEVICE:
4775 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4776 default:
4777 return DEVICE_CATEGORY_SPEAKER;
4778 }
4779}
4780
Eric Laurente0720872014-03-11 09:30:41 -07004781float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004782 int indexInUi)
4783{
4784 device_category deviceCategory = getDeviceCategory(device);
4785 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4786
4787 // the volume index in the UI is relative to the min and max volume indices for this stream type
4788 int nbSteps = 1 + curve[VOLMAX].mIndex -
4789 curve[VOLMIN].mIndex;
4790 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4791 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4792
4793 // find what part of the curve this index volume belongs to, or if it's out of bounds
4794 int segment = 0;
4795 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4796 return 0.0f;
4797 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4798 segment = 0;
4799 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4800 segment = 1;
4801 } else if (volIdx <= curve[VOLMAX].mIndex) {
4802 segment = 2;
4803 } else { // out of bounds
4804 return 1.0f;
4805 }
4806
4807 // linear interpolation in the attenuation table in dB
4808 float decibels = curve[segment].mDBAttenuation +
4809 ((float)(volIdx - curve[segment].mIndex)) *
4810 ( (curve[segment+1].mDBAttenuation -
4811 curve[segment].mDBAttenuation) /
4812 ((float)(curve[segment+1].mIndex -
4813 curve[segment].mIndex)) );
4814
4815 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4816
4817 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4818 curve[segment].mIndex, volIdx,
4819 curve[segment+1].mIndex,
4820 curve[segment].mDBAttenuation,
4821 decibels,
4822 curve[segment+1].mDBAttenuation,
4823 amplification);
4824
4825 return amplification;
4826}
4827
Eric Laurente0720872014-03-11 09:30:41 -07004828const AudioPolicyManager::VolumeCurvePoint
4829 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004830 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4831};
4832
Eric Laurente0720872014-03-11 09:30:41 -07004833const AudioPolicyManager::VolumeCurvePoint
4834 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004835 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4836};
4837
Eric Laurente0720872014-03-11 09:30:41 -07004838const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004839 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4840 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4841};
4842
4843const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004844 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004845 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4846};
4847
Eric Laurente0720872014-03-11 09:30:41 -07004848const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004849 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004850 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004851};
4852
4853const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004854 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004855 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4856};
4857
Eric Laurente0720872014-03-11 09:30:41 -07004858const AudioPolicyManager::VolumeCurvePoint
4859 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004860 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4861};
4862
4863// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4864// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4865// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4866// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4867
Eric Laurente0720872014-03-11 09:30:41 -07004868const AudioPolicyManager::VolumeCurvePoint
4869 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004870 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4871};
4872
Eric Laurente0720872014-03-11 09:30:41 -07004873const AudioPolicyManager::VolumeCurvePoint
4874 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004875 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4876};
4877
Eric Laurente0720872014-03-11 09:30:41 -07004878const AudioPolicyManager::VolumeCurvePoint
4879 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004880 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4881};
4882
Eric Laurente0720872014-03-11 09:30:41 -07004883const AudioPolicyManager::VolumeCurvePoint
4884 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004885 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4886};
4887
Eric Laurente0720872014-03-11 09:30:41 -07004888const AudioPolicyManager::VolumeCurvePoint
4889 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004890 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4891};
4892
Eric Laurente0720872014-03-11 09:30:41 -07004893const AudioPolicyManager::VolumeCurvePoint
4894 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4895 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004896 { // AUDIO_STREAM_VOICE_CALL
4897 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4898 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004899 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4900 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004901 },
4902 { // AUDIO_STREAM_SYSTEM
4903 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4904 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004905 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4906 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004907 },
4908 { // AUDIO_STREAM_RING
4909 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4910 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004911 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4912 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004913 },
4914 { // AUDIO_STREAM_MUSIC
4915 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4916 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004917 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4918 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004919 },
4920 { // AUDIO_STREAM_ALARM
4921 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4922 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004923 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4924 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004925 },
4926 { // AUDIO_STREAM_NOTIFICATION
4927 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4928 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004929 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4930 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004931 },
4932 { // AUDIO_STREAM_BLUETOOTH_SCO
4933 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4934 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004935 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4936 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004937 },
4938 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4939 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4940 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004941 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4942 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004943 },
4944 { // AUDIO_STREAM_DTMF
4945 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4946 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004947 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4948 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004949 },
4950 { // AUDIO_STREAM_TTS
4951 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4952 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004953 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4954 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004955 },
4956};
4957
Eric Laurente0720872014-03-11 09:30:41 -07004958void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004959{
4960 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4961 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4962 mStreams[i].mVolumeCurve[j] =
4963 sVolumeProfiles[i][j];
4964 }
4965 }
4966
4967 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4968 if (mSpeakerDrcEnabled) {
4969 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4970 sDefaultSystemVolumeCurveDrc;
4971 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4972 sSpeakerSonificationVolumeCurveDrc;
4973 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4974 sSpeakerSonificationVolumeCurveDrc;
4975 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4976 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004977 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4978 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004979 }
4980}
4981
Eric Laurente0720872014-03-11 09:30:41 -07004982float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004983 int index,
4984 audio_io_handle_t output,
4985 audio_devices_t device)
4986{
4987 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004988 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004989 StreamDescriptor &streamDesc = mStreams[stream];
4990
4991 if (device == AUDIO_DEVICE_NONE) {
4992 device = outputDesc->device();
4993 }
4994
Eric Laurente552edb2014-03-10 17:42:56 -07004995 volume = volIndexToAmpl(device, streamDesc, index);
4996
4997 // if a headset is connected, apply the following rules to ring tones and notifications
4998 // to avoid sound level bursts in user's ears:
4999 // - always attenuate ring tones and notifications volume by 6dB
5000 // - if music is playing, always limit the volume to current music volume,
5001 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005002 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005003 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5004 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5005 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5006 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5007 ((stream_strategy == STRATEGY_SONIFICATION)
5008 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005009 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005010 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005011 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005012 streamDesc.mCanBeMuted) {
5013 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5014 // when the phone is ringing we must consider that music could have been paused just before
5015 // by the music application and behave as if music was active if the last music track was
5016 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005017 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005018 mLimitRingtoneVolume) {
5019 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005020 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5021 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005022 output,
5023 musicDevice);
5024 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5025 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5026 if (volume > minVol) {
5027 volume = minVol;
5028 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5029 }
5030 }
5031 }
5032
5033 return volume;
5034}
5035
Eric Laurente0720872014-03-11 09:30:41 -07005036status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005037 int index,
5038 audio_io_handle_t output,
5039 audio_devices_t device,
5040 int delayMs,
5041 bool force)
5042{
5043
5044 // do not change actual stream volume if the stream is muted
5045 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5046 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5047 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5048 return NO_ERROR;
5049 }
5050
5051 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005052 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5053 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5054 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5055 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005056 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005057 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005058 return INVALID_OPERATION;
5059 }
5060
5061 float volume = computeVolume(stream, index, output, device);
5062 // We actually change the volume if:
5063 // - the float value returned by computeVolume() changed
5064 // - the force flag is set
5065 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5066 force) {
5067 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5068 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5069 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5070 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005071 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5072 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005073 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005074 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005075 }
5076
Eric Laurent3b73df72014-03-11 09:06:29 -07005077 if (stream == AUDIO_STREAM_VOICE_CALL ||
5078 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005079 float voiceVolume;
5080 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005081 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005082 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5083 } else {
5084 voiceVolume = 1.0;
5085 }
5086
5087 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5088 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5089 mLastVoiceVolume = voiceVolume;
5090 }
5091 }
5092
5093 return NO_ERROR;
5094}
5095
Eric Laurente0720872014-03-11 09:30:41 -07005096void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005097 audio_devices_t device,
5098 int delayMs,
5099 bool force)
5100{
5101 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5102
Eric Laurent3b73df72014-03-11 09:06:29 -07005103 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5104 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005105 mStreams[stream].getVolumeIndex(device),
5106 output,
5107 device,
5108 delayMs,
5109 force);
5110 }
5111}
5112
Eric Laurente0720872014-03-11 09:30:41 -07005113void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005114 bool on,
5115 audio_io_handle_t output,
5116 int delayMs,
5117 audio_devices_t device)
5118{
5119 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005120 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5121 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5122 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005123 }
5124 }
5125}
5126
Eric Laurente0720872014-03-11 09:30:41 -07005127void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005128 bool on,
5129 audio_io_handle_t output,
5130 int delayMs,
5131 audio_devices_t device)
5132{
5133 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005134 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005135 if (device == AUDIO_DEVICE_NONE) {
5136 device = outputDesc->device();
5137 }
5138
5139 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5140 stream, on, output, outputDesc->mMuteCount[stream], device);
5141
5142 if (on) {
5143 if (outputDesc->mMuteCount[stream] == 0) {
5144 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005145 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5146 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005147 checkAndSetVolume(stream, 0, output, device, delayMs);
5148 }
5149 }
5150 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5151 outputDesc->mMuteCount[stream]++;
5152 } else {
5153 if (outputDesc->mMuteCount[stream] == 0) {
5154 ALOGV("setStreamMute() unmuting non muted stream!");
5155 return;
5156 }
5157 if (--outputDesc->mMuteCount[stream] == 0) {
5158 checkAndSetVolume(stream,
5159 streamDesc.getVolumeIndex(device),
5160 output,
5161 device,
5162 delayMs);
5163 }
5164 }
5165}
5166
Eric Laurente0720872014-03-11 09:30:41 -07005167void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005168 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005169{
5170 // if the stream pertains to sonification strategy and we are in call we must
5171 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5172 // in the device used for phone strategy and play the tone if the selected device does not
5173 // interfere with the device used for phone strategy
5174 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5175 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005176 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005177 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5178 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005179 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005180 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5181 stream, starting, outputDesc->mDevice, stateChange);
5182 if (outputDesc->mRefCount[stream]) {
5183 int muteCount = 1;
5184 if (stateChange) {
5185 muteCount = outputDesc->mRefCount[stream];
5186 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005187 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005188 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5189 for (int i = 0; i < muteCount; i++) {
5190 setStreamMute(stream, starting, mPrimaryOutput);
5191 }
5192 } else {
5193 ALOGV("handleIncallSonification() high visibility");
5194 if (outputDesc->device() &
5195 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5196 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5197 for (int i = 0; i < muteCount; i++) {
5198 setStreamMute(stream, starting, mPrimaryOutput);
5199 }
5200 }
5201 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005202 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5203 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005204 } else {
5205 mpClientInterface->stopTone();
5206 }
5207 }
5208 }
5209 }
5210}
5211
Eric Laurente0720872014-03-11 09:30:41 -07005212bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005213{
5214 return isStateInCall(mPhoneState);
5215}
5216
Eric Laurente0720872014-03-11 09:30:41 -07005217bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005218 return ((state == AUDIO_MODE_IN_CALL) ||
5219 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005220}
5221
Eric Laurente0720872014-03-11 09:30:41 -07005222uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005223{
5224 return MAX_EFFECTS_CPU_LOAD;
5225}
5226
Eric Laurente0720872014-03-11 09:30:41 -07005227uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005228{
5229 return MAX_EFFECTS_MEMORY;
5230}
5231
Eric Laurent6a94d692014-05-20 11:18:06 -07005232
Eric Laurente552edb2014-03-10 17:42:56 -07005233// --- AudioOutputDescriptor class implementation
5234
Eric Laurente0720872014-03-11 09:30:41 -07005235AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005236 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005237 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005238 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005239 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5240{
5241 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005242 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005243 mRefCount[i] = 0;
5244 mCurVolume[i] = -1.0;
5245 mMuteCount[i] = 0;
5246 mStopTime[i] = 0;
5247 }
5248 for (int i = 0; i < NUM_STRATEGIES; i++) {
5249 mStrategyMutedByDevice[i] = false;
5250 }
5251 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005252 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005253 mSamplingRate = profile->pickSamplingRate();
5254 mFormat = profile->pickFormat();
5255 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005256 if (profile->mGains.size() > 0) {
5257 profile->mGains[0]->getDefaultConfig(&mGain);
5258 }
Eric Laurente552edb2014-03-10 17:42:56 -07005259 }
5260}
5261
Eric Laurente0720872014-03-11 09:30:41 -07005262audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005263{
5264 if (isDuplicated()) {
5265 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5266 } else {
5267 return mDevice;
5268 }
5269}
5270
Eric Laurente0720872014-03-11 09:30:41 -07005271uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005272{
5273 if (isDuplicated()) {
5274 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5275 } else {
5276 return mLatency;
5277 }
5278}
5279
Eric Laurente0720872014-03-11 09:30:41 -07005280bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005281 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005282{
5283 if (isDuplicated()) {
5284 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5285 } else if (outputDesc->isDuplicated()){
5286 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5287 } else {
5288 return (mProfile->mModule == outputDesc->mProfile->mModule);
5289 }
5290}
5291
Eric Laurente0720872014-03-11 09:30:41 -07005292void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005293 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005294{
5295 // forward usage count change to attached outputs
5296 if (isDuplicated()) {
5297 mOutput1->changeRefCount(stream, delta);
5298 mOutput2->changeRefCount(stream, delta);
5299 }
5300 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005301 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5302 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005303 mRefCount[stream] = 0;
5304 return;
5305 }
5306 mRefCount[stream] += delta;
5307 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5308}
5309
Eric Laurente0720872014-03-11 09:30:41 -07005310audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005311{
5312 if (isDuplicated()) {
5313 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5314 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005315 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005316 }
5317}
5318
Eric Laurente0720872014-03-11 09:30:41 -07005319bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005320{
5321 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5322}
5323
Eric Laurente0720872014-03-11 09:30:41 -07005324bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005325 uint32_t inPastMs,
5326 nsecs_t sysTime) const
5327{
5328 if ((sysTime == 0) && (inPastMs != 0)) {
5329 sysTime = systemTime();
5330 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005331 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5332 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005333 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005334 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005335 return true;
5336 }
5337 }
5338 return false;
5339}
5340
Eric Laurente0720872014-03-11 09:30:41 -07005341bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005342 uint32_t inPastMs,
5343 nsecs_t sysTime) const
5344{
5345 if (mRefCount[stream] != 0) {
5346 return true;
5347 }
5348 if (inPastMs == 0) {
5349 return false;
5350 }
5351 if (sysTime == 0) {
5352 sysTime = systemTime();
5353 }
5354 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5355 return true;
5356 }
5357 return false;
5358}
5359
Eric Laurent1c333e22014-05-20 10:48:17 -07005360void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005361 struct audio_port_config *dstConfig,
5362 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005363{
Eric Laurent84c70242014-06-23 08:46:27 -07005364 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5365
Eric Laurent1f2f2232014-06-02 12:01:23 -07005366 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5367 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5368 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005369 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005370 }
5371 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5372
Eric Laurent6a94d692014-05-20 11:18:06 -07005373 dstConfig->id = mId;
5374 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5375 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005376 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5377 dstConfig->ext.mix.handle = mIoHandle;
5378 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005379}
5380
5381void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5382 struct audio_port *port) const
5383{
Eric Laurent84c70242014-06-23 08:46:27 -07005384 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005385 mProfile->toAudioPort(port);
5386 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005387 toAudioPortConfig(&port->active_config);
5388 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005389 port->ext.mix.handle = mIoHandle;
5390 port->ext.mix.latency_class =
5391 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5392}
Eric Laurente552edb2014-03-10 17:42:56 -07005393
Eric Laurente0720872014-03-11 09:30:41 -07005394status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005395{
5396 const size_t SIZE = 256;
5397 char buffer[SIZE];
5398 String8 result;
5399
Eric Laurent4d416952014-08-10 14:07:09 -07005400 snprintf(buffer, SIZE, " ID: %d\n", mId);
5401 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005402 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5403 result.append(buffer);
5404 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5405 result.append(buffer);
5406 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5407 result.append(buffer);
5408 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5409 result.append(buffer);
5410 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5411 result.append(buffer);
5412 snprintf(buffer, SIZE, " Devices %08x\n", device());
5413 result.append(buffer);
5414 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5415 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005416 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5417 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5418 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005419 result.append(buffer);
5420 }
5421 write(fd, result.string(), result.size());
5422
5423 return NO_ERROR;
5424}
5425
5426// --- AudioInputDescriptor class implementation
5427
Eric Laurent1c333e22014-05-20 10:48:17 -07005428AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005429 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005430 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005431 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005432{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005433 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005434 mSamplingRate = profile->pickSamplingRate();
5435 mFormat = profile->pickFormat();
5436 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005437 if (profile->mGains.size() > 0) {
5438 profile->mGains[0]->getDefaultConfig(&mGain);
5439 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005440 }
Eric Laurente552edb2014-03-10 17:42:56 -07005441}
5442
Eric Laurent1c333e22014-05-20 10:48:17 -07005443void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005444 struct audio_port_config *dstConfig,
5445 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005446{
Eric Laurent84c70242014-06-23 08:46:27 -07005447 ALOG_ASSERT(mProfile != 0,
5448 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005449 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5450 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5451 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005452 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005453 }
5454
5455 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5456
Eric Laurent6a94d692014-05-20 11:18:06 -07005457 dstConfig->id = mId;
5458 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5459 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005460 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5461 dstConfig->ext.mix.handle = mIoHandle;
5462 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005463}
5464
5465void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5466 struct audio_port *port) const
5467{
Eric Laurent84c70242014-06-23 08:46:27 -07005468 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5469
Eric Laurent1c333e22014-05-20 10:48:17 -07005470 mProfile->toAudioPort(port);
5471 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005472 toAudioPortConfig(&port->active_config);
5473 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005474 port->ext.mix.handle = mIoHandle;
5475 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5476}
5477
Eric Laurente0720872014-03-11 09:30:41 -07005478status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005479{
5480 const size_t SIZE = 256;
5481 char buffer[SIZE];
5482 String8 result;
5483
Eric Laurent4d416952014-08-10 14:07:09 -07005484 snprintf(buffer, SIZE, " ID: %d\n", mId);
5485 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005486 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5487 result.append(buffer);
5488 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5489 result.append(buffer);
5490 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5491 result.append(buffer);
5492 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5493 result.append(buffer);
5494 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5495 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005496 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5497 result.append(buffer);
5498
Eric Laurente552edb2014-03-10 17:42:56 -07005499 write(fd, result.string(), result.size());
5500
5501 return NO_ERROR;
5502}
5503
5504// --- StreamDescriptor class implementation
5505
Eric Laurente0720872014-03-11 09:30:41 -07005506AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005507 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5508{
5509 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5510}
5511
Eric Laurente0720872014-03-11 09:30:41 -07005512int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005513{
Eric Laurente0720872014-03-11 09:30:41 -07005514 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005515 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5516 if (mIndexCur.indexOfKey(device) < 0) {
5517 device = AUDIO_DEVICE_OUT_DEFAULT;
5518 }
5519 return mIndexCur.valueFor(device);
5520}
5521
Eric Laurente0720872014-03-11 09:30:41 -07005522void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005523{
5524 const size_t SIZE = 256;
5525 char buffer[SIZE];
5526 String8 result;
5527
5528 snprintf(buffer, SIZE, "%s %02d %02d ",
5529 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5530 result.append(buffer);
5531 for (size_t i = 0; i < mIndexCur.size(); i++) {
5532 snprintf(buffer, SIZE, "%04x : %02d, ",
5533 mIndexCur.keyAt(i),
5534 mIndexCur.valueAt(i));
5535 result.append(buffer);
5536 }
5537 result.append("\n");
5538
5539 write(fd, result.string(), result.size());
5540}
5541
5542// --- EffectDescriptor class implementation
5543
Eric Laurente0720872014-03-11 09:30:41 -07005544status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005545{
5546 const size_t SIZE = 256;
5547 char buffer[SIZE];
5548 String8 result;
5549
5550 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5551 result.append(buffer);
5552 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5553 result.append(buffer);
5554 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5555 result.append(buffer);
5556 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5557 result.append(buffer);
5558 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5559 result.append(buffer);
5560 write(fd, result.string(), result.size());
5561
5562 return NO_ERROR;
5563}
5564
Eric Laurent1c333e22014-05-20 10:48:17 -07005565// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005566
Eric Laurente0720872014-03-11 09:30:41 -07005567AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005568 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5569 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005570{
5571}
5572
Eric Laurente0720872014-03-11 09:30:41 -07005573AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005574{
5575 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005576 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005577 }
5578 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005579 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005580 }
5581 free((void *)mName);
5582}
5583
Eric Laurent1afeecb2014-05-14 08:52:28 -07005584status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5585{
5586 cnode *node = root->first_child;
5587
5588 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5589
5590 while (node) {
5591 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5592 profile->loadSamplingRates((char *)node->value);
5593 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5594 profile->loadFormats((char *)node->value);
5595 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5596 profile->loadInChannels((char *)node->value);
5597 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5598 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5599 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07005600 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5601 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005602 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5603 profile->loadGains(node);
5604 }
5605 node = node->next;
5606 }
5607 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5608 "loadInput() invalid supported devices");
5609 ALOGW_IF(profile->mChannelMasks.size() == 0,
5610 "loadInput() invalid supported channel masks");
5611 ALOGW_IF(profile->mSamplingRates.size() == 0,
5612 "loadInput() invalid supported sampling rates");
5613 ALOGW_IF(profile->mFormats.size() == 0,
5614 "loadInput() invalid supported formats");
5615 if (!profile->mSupportedDevices.isEmpty() &&
5616 (profile->mChannelMasks.size() != 0) &&
5617 (profile->mSamplingRates.size() != 0) &&
5618 (profile->mFormats.size() != 0)) {
5619
5620 ALOGV("loadInput() adding input Supported Devices %04x",
5621 profile->mSupportedDevices.types());
5622
5623 mInputProfiles.add(profile);
5624 return NO_ERROR;
5625 } else {
5626 return BAD_VALUE;
5627 }
5628}
5629
5630status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5631{
5632 cnode *node = root->first_child;
5633
5634 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5635
5636 while (node) {
5637 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5638 profile->loadSamplingRates((char *)node->value);
5639 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5640 profile->loadFormats((char *)node->value);
5641 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5642 profile->loadOutChannels((char *)node->value);
5643 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5644 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5645 mDeclaredDevices);
5646 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005647 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005648 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5649 profile->loadGains(node);
5650 }
5651 node = node->next;
5652 }
5653 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5654 "loadOutput() invalid supported devices");
5655 ALOGW_IF(profile->mChannelMasks.size() == 0,
5656 "loadOutput() invalid supported channel masks");
5657 ALOGW_IF(profile->mSamplingRates.size() == 0,
5658 "loadOutput() invalid supported sampling rates");
5659 ALOGW_IF(profile->mFormats.size() == 0,
5660 "loadOutput() invalid supported formats");
5661 if (!profile->mSupportedDevices.isEmpty() &&
5662 (profile->mChannelMasks.size() != 0) &&
5663 (profile->mSamplingRates.size() != 0) &&
5664 (profile->mFormats.size() != 0)) {
5665
5666 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5667 profile->mSupportedDevices.types(), profile->mFlags);
5668
5669 mOutputProfiles.add(profile);
5670 return NO_ERROR;
5671 } else {
5672 return BAD_VALUE;
5673 }
5674}
5675
5676status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5677{
5678 cnode *node = root->first_child;
5679
5680 audio_devices_t type = AUDIO_DEVICE_NONE;
5681 while (node) {
5682 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5683 type = parseDeviceNames((char *)node->value);
5684 break;
5685 }
5686 node = node->next;
5687 }
5688 if (type == AUDIO_DEVICE_NONE ||
5689 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5690 ALOGW("loadDevice() bad type %08x", type);
5691 return BAD_VALUE;
5692 }
5693 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5694 deviceDesc->mModule = this;
5695
5696 node = root->first_child;
5697 while (node) {
5698 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5699 deviceDesc->mAddress = String8((char *)node->value);
5700 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5701 if (audio_is_input_device(type)) {
5702 deviceDesc->loadInChannels((char *)node->value);
5703 } else {
5704 deviceDesc->loadOutChannels((char *)node->value);
5705 }
5706 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5707 deviceDesc->loadGains(node);
5708 }
5709 node = node->next;
5710 }
5711
5712 ALOGV("loadDevice() adding device name %s type %08x address %s",
5713 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5714
5715 mDeclaredDevices.add(deviceDesc);
5716
5717 return NO_ERROR;
5718}
5719
Eric Laurente0720872014-03-11 09:30:41 -07005720void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005721{
5722 const size_t SIZE = 256;
5723 char buffer[SIZE];
5724 String8 result;
5725
5726 snprintf(buffer, SIZE, " - name: %s\n", mName);
5727 result.append(buffer);
5728 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5729 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005730 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5731 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005732 write(fd, result.string(), result.size());
5733 if (mOutputProfiles.size()) {
5734 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5735 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005736 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005737 write(fd, buffer, strlen(buffer));
5738 mOutputProfiles[i]->dump(fd);
5739 }
5740 }
5741 if (mInputProfiles.size()) {
5742 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5743 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005744 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005745 write(fd, buffer, strlen(buffer));
5746 mInputProfiles[i]->dump(fd);
5747 }
5748 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005749 if (mDeclaredDevices.size()) {
5750 write(fd, " - devices:\n", strlen(" - devices:\n"));
5751 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5752 mDeclaredDevices[i]->dump(fd, 4, i);
5753 }
5754 }
Eric Laurente552edb2014-03-10 17:42:56 -07005755}
5756
Eric Laurent1c333e22014-05-20 10:48:17 -07005757// --- AudioPort class implementation
5758
Eric Laurenta121f902014-06-03 13:32:54 -07005759
5760AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5761 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07005762 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07005763{
5764 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5765 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5766}
5767
Eric Laurent1c333e22014-05-20 10:48:17 -07005768void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5769{
5770 port->role = mRole;
5771 port->type = mType;
5772 unsigned int i;
5773 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005774 if (mSamplingRates[i] != 0) {
5775 port->sample_rates[i] = mSamplingRates[i];
5776 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005777 }
5778 port->num_sample_rates = i;
5779 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005780 if (mChannelMasks[i] != 0) {
5781 port->channel_masks[i] = mChannelMasks[i];
5782 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005783 }
5784 port->num_channel_masks = i;
5785 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005786 if (mFormats[i] != 0) {
5787 port->formats[i] = mFormats[i];
5788 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005789 }
5790 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005791
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005792 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005793
5794 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5795 port->gains[i] = mGains[i]->mGain;
5796 }
5797 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005798}
5799
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005800void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
5801 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
5802 const uint32_t rate = port->mSamplingRates.itemAt(k);
5803 if (rate != 0) { // skip "dynamic" rates
5804 bool hasRate = false;
5805 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
5806 if (rate == mSamplingRates.itemAt(l)) {
5807 hasRate = true;
5808 break;
5809 }
5810 }
5811 if (!hasRate) { // never import a sampling rate twice
5812 mSamplingRates.add(rate);
5813 }
5814 }
5815 }
5816 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
5817 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
5818 if (mask != 0) { // skip "dynamic" masks
5819 bool hasMask = false;
5820 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
5821 if (mask == mChannelMasks.itemAt(l)) {
5822 hasMask = true;
5823 break;
5824 }
5825 }
5826 if (!hasMask) { // never import a channel mask twice
5827 mChannelMasks.add(mask);
5828 }
5829 }
5830 }
5831 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
5832 const audio_format_t format = port->mFormats.itemAt(k);
5833 if (format != 0) { // skip "dynamic" formats
5834 bool hasFormat = false;
5835 for (size_t l = 0 ; l < mFormats.size() ; l++) {
5836 if (format == mFormats.itemAt(l)) {
5837 hasFormat = true;
5838 break;
5839 }
5840 }
5841 if (!hasFormat) { // never import a channel mask twice
5842 mFormats.add(format);
5843 }
5844 }
5845 }
5846}
5847
5848void AudioPolicyManager::AudioPort::clearCapabilities() {
5849 mChannelMasks.clear();
5850 mFormats.clear();
5851 mSamplingRates.clear();
5852}
Eric Laurent1c333e22014-05-20 10:48:17 -07005853
5854void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5855{
5856 char *str = strtok(name, "|");
5857
5858 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5859 // rates should be read from the output stream after it is opened for the first time
5860 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5861 mSamplingRates.add(0);
5862 return;
5863 }
5864
5865 while (str != NULL) {
5866 uint32_t rate = atoi(str);
5867 if (rate != 0) {
5868 ALOGV("loadSamplingRates() adding rate %d", rate);
5869 mSamplingRates.add(rate);
5870 }
5871 str = strtok(NULL, "|");
5872 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005873}
5874
5875void AudioPolicyManager::AudioPort::loadFormats(char *name)
5876{
5877 char *str = strtok(name, "|");
5878
5879 // by convention, "0' in the first entry in mFormats indicates the supported formats
5880 // should be read from the output stream after it is opened for the first time
5881 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5882 mFormats.add(AUDIO_FORMAT_DEFAULT);
5883 return;
5884 }
5885
5886 while (str != NULL) {
5887 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5888 ARRAY_SIZE(sFormatNameToEnumTable),
5889 str);
5890 if (format != AUDIO_FORMAT_DEFAULT) {
5891 mFormats.add(format);
5892 }
5893 str = strtok(NULL, "|");
5894 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005895}
5896
5897void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5898{
5899 const char *str = strtok(name, "|");
5900
5901 ALOGV("loadInChannels() %s", name);
5902
5903 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5904 mChannelMasks.add(0);
5905 return;
5906 }
5907
5908 while (str != NULL) {
5909 audio_channel_mask_t channelMask =
5910 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5911 ARRAY_SIZE(sInChannelsNameToEnumTable),
5912 str);
5913 if (channelMask != 0) {
5914 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5915 mChannelMasks.add(channelMask);
5916 }
5917 str = strtok(NULL, "|");
5918 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005919}
5920
5921void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5922{
5923 const char *str = strtok(name, "|");
5924
5925 ALOGV("loadOutChannels() %s", name);
5926
5927 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5928 // masks should be read from the output stream after it is opened for the first time
5929 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5930 mChannelMasks.add(0);
5931 return;
5932 }
5933
5934 while (str != NULL) {
5935 audio_channel_mask_t channelMask =
5936 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5937 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5938 str);
5939 if (channelMask != 0) {
5940 mChannelMasks.add(channelMask);
5941 }
5942 str = strtok(NULL, "|");
5943 }
5944 return;
5945}
5946
Eric Laurent1afeecb2014-05-14 08:52:28 -07005947audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5948{
5949 const char *str = strtok(name, "|");
5950
5951 ALOGV("loadGainMode() %s", name);
5952 audio_gain_mode_t mode = 0;
5953 while (str != NULL) {
5954 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5955 ARRAY_SIZE(sGainModeNameToEnumTable),
5956 str);
5957 str = strtok(NULL, "|");
5958 }
5959 return mode;
5960}
5961
Eric Laurenta121f902014-06-03 13:32:54 -07005962void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005963{
5964 cnode *node = root->first_child;
5965
Eric Laurenta121f902014-06-03 13:32:54 -07005966 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005967
5968 while (node) {
5969 if (strcmp(node->name, GAIN_MODE) == 0) {
5970 gain->mGain.mode = loadGainMode((char *)node->value);
5971 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005972 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005973 gain->mGain.channel_mask =
5974 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5975 ARRAY_SIZE(sInChannelsNameToEnumTable),
5976 (char *)node->value);
5977 } else {
5978 gain->mGain.channel_mask =
5979 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5980 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5981 (char *)node->value);
5982 }
5983 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5984 gain->mGain.min_value = atoi((char *)node->value);
5985 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5986 gain->mGain.max_value = atoi((char *)node->value);
5987 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5988 gain->mGain.default_value = atoi((char *)node->value);
5989 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5990 gain->mGain.step_value = atoi((char *)node->value);
5991 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5992 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5993 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5994 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5995 }
5996 node = node->next;
5997 }
5998
5999 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6000 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6001
6002 if (gain->mGain.mode == 0) {
6003 return;
6004 }
6005 mGains.add(gain);
6006}
6007
6008void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6009{
6010 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006011 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006012 while (node) {
6013 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006014 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006015 node = node->next;
6016 }
6017}
6018
Glenn Kastencbd48022014-07-24 13:46:44 -07006019status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006020{
6021 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6022 if (mSamplingRates[i] == samplingRate) {
6023 return NO_ERROR;
6024 }
6025 }
6026 return BAD_VALUE;
6027}
6028
Glenn Kastencbd48022014-07-24 13:46:44 -07006029status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6030 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006031{
Glenn Kastencbd48022014-07-24 13:46:44 -07006032 // Search for the closest supported sampling rate that is above (preferred)
6033 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6034 // The sampling rates do not need to be sorted in ascending order.
6035 ssize_t maxBelow = -1;
6036 ssize_t minAbove = -1;
6037 uint32_t candidate;
6038 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6039 candidate = mSamplingRates[i];
6040 if (candidate == samplingRate) {
6041 if (updatedSamplingRate != NULL) {
6042 *updatedSamplingRate = candidate;
6043 }
6044 return NO_ERROR;
6045 }
6046 // candidate < desired
6047 if (candidate < samplingRate) {
6048 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6049 maxBelow = i;
6050 }
6051 // candidate > desired
6052 } else {
6053 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6054 minAbove = i;
6055 }
6056 }
6057 }
6058 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6059 // TODO Move these assumptions out.
6060 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6061 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6062 // due to approximation by an int32_t of the
6063 // phase increments
6064 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6065 if (minAbove >= 0) {
6066 candidate = mSamplingRates[minAbove];
6067 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6068 if (updatedSamplingRate != NULL) {
6069 *updatedSamplingRate = candidate;
6070 }
6071 return NO_ERROR;
6072 }
6073 }
6074 // But if we have to up-sample from a lower sampling rate, that's OK.
6075 if (maxBelow >= 0) {
6076 candidate = mSamplingRates[maxBelow];
6077 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6078 if (updatedSamplingRate != NULL) {
6079 *updatedSamplingRate = candidate;
6080 }
6081 return NO_ERROR;
6082 }
6083 }
6084 // leave updatedSamplingRate unmodified
6085 return BAD_VALUE;
6086}
6087
6088status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6089{
6090 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006091 if (mChannelMasks[i] == channelMask) {
6092 return NO_ERROR;
6093 }
6094 }
6095 return BAD_VALUE;
6096}
6097
Glenn Kastencbd48022014-07-24 13:46:44 -07006098status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6099 const
6100{
6101 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6102 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6103 // FIXME Does not handle multi-channel automatic conversions yet
6104 audio_channel_mask_t supported = mChannelMasks[i];
6105 if (supported == channelMask) {
6106 return NO_ERROR;
6107 }
6108 if (isRecordThread) {
6109 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6110 // FIXME Abstract this out to a table.
6111 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6112 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6113 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6114 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6115 return NO_ERROR;
6116 }
6117 }
6118 }
6119 return BAD_VALUE;
6120}
6121
Eric Laurenta121f902014-06-03 13:32:54 -07006122status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6123{
6124 for (size_t i = 0; i < mFormats.size(); i ++) {
6125 if (mFormats[i] == format) {
6126 return NO_ERROR;
6127 }
6128 }
6129 return BAD_VALUE;
6130}
6131
Eric Laurent1e693b52014-07-09 15:03:28 -07006132
6133uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6134{
6135 // special case for uninitialized dynamic profile
6136 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6137 return 0;
6138 }
6139
Eric Laurent828bcff2014-09-07 12:26:06 -07006140 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6141 // channel count / sampling rate combination chosen will be supported by the connected
6142 // sink
6143 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6144 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6145 uint32_t samplingRate = UINT_MAX;
6146 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6147 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6148 samplingRate = mSamplingRates[i];
6149 }
6150 }
6151 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6152 }
6153
Eric Laurent1e693b52014-07-09 15:03:28 -07006154 uint32_t samplingRate = 0;
6155 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6156
6157 // For mixed output and inputs, use max mixer sampling rates. Do not
6158 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006159 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006160 maxRate = UINT_MAX;
6161 }
6162 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6163 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6164 samplingRate = mSamplingRates[i];
6165 }
6166 }
6167 return samplingRate;
6168}
6169
6170audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6171{
6172 // special case for uninitialized dynamic profile
6173 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6174 return AUDIO_CHANNEL_NONE;
6175 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006176 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006177
6178 // For direct outputs, pick minimum channel count: this helps ensuring that the
6179 // channel count / sampling rate combination chosen will be supported by the connected
6180 // sink
6181 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6182 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6183 uint32_t channelCount = UINT_MAX;
6184 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6185 uint32_t cnlCount;
6186 if (mUseInChannelMask) {
6187 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6188 } else {
6189 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6190 }
6191 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6192 channelMask = mChannelMasks[i];
6193 channelCount = cnlCount;
6194 }
6195 }
6196 return channelMask;
6197 }
6198
Eric Laurent1e693b52014-07-09 15:03:28 -07006199 uint32_t channelCount = 0;
6200 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6201
6202 // For mixed output and inputs, use max mixer channel count. Do not
6203 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006204 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006205 maxCount = UINT_MAX;
6206 }
6207 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6208 uint32_t cnlCount;
6209 if (mUseInChannelMask) {
6210 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6211 } else {
6212 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6213 }
6214 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6215 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006216 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006217 }
6218 }
6219 return channelMask;
6220}
6221
Andy Hung9a605382014-07-28 16:16:31 -07006222/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006223const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6224 AUDIO_FORMAT_DEFAULT,
6225 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006226 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006227 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006228 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006229 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006230};
6231
6232int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6233 audio_format_t format2)
6234{
6235 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6236 // compressed format and better than any PCM format. This is by design of pickFormat()
6237 if (!audio_is_linear_pcm(format1)) {
6238 if (!audio_is_linear_pcm(format2)) {
6239 return 0;
6240 }
6241 return 1;
6242 }
6243 if (!audio_is_linear_pcm(format2)) {
6244 return -1;
6245 }
6246
6247 int index1 = -1, index2 = -1;
6248 for (size_t i = 0;
6249 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6250 i ++) {
6251 if (sPcmFormatCompareTable[i] == format1) {
6252 index1 = i;
6253 }
6254 if (sPcmFormatCompareTable[i] == format2) {
6255 index2 = i;
6256 }
6257 }
6258 // format1 not found => index1 < 0 => format2 > format1
6259 // format2 not found => index2 < 0 => format2 < format1
6260 return index1 - index2;
6261}
6262
6263audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6264{
6265 // special case for uninitialized dynamic profile
6266 if (mFormats.size() == 1 && mFormats[0] == 0) {
6267 return AUDIO_FORMAT_DEFAULT;
6268 }
6269
6270 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006271 audio_format_t bestFormat =
6272 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6273 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006274 // For mixed output and inputs, use best mixer output format. Do not
6275 // limit format otherwise
6276 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6277 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006278 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006279 bestFormat = AUDIO_FORMAT_INVALID;
6280 }
6281
6282 for (size_t i = 0; i < mFormats.size(); i ++) {
6283 if ((compareFormats(mFormats[i], format) > 0) &&
6284 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6285 format = mFormats[i];
6286 }
6287 }
6288 return format;
6289}
6290
Eric Laurenta121f902014-06-03 13:32:54 -07006291status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6292 int index) const
6293{
6294 if (index < 0 || (size_t)index >= mGains.size()) {
6295 return BAD_VALUE;
6296 }
6297 return mGains[index]->checkConfig(gainConfig);
6298}
6299
Eric Laurent1afeecb2014-05-14 08:52:28 -07006300void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6301{
6302 const size_t SIZE = 256;
6303 char buffer[SIZE];
6304 String8 result;
6305
6306 if (mName.size() != 0) {
6307 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6308 result.append(buffer);
6309 }
6310
6311 if (mSamplingRates.size() != 0) {
6312 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6313 result.append(buffer);
6314 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006315 if (i == 0 && mSamplingRates[i] == 0) {
6316 snprintf(buffer, SIZE, "Dynamic");
6317 } else {
6318 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6319 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006320 result.append(buffer);
6321 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6322 }
6323 result.append("\n");
6324 }
6325
6326 if (mChannelMasks.size() != 0) {
6327 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6328 result.append(buffer);
6329 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006330 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6331
6332 if (i == 0 && mChannelMasks[i] == 0) {
6333 snprintf(buffer, SIZE, "Dynamic");
6334 } else {
6335 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6336 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006337 result.append(buffer);
6338 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6339 }
6340 result.append("\n");
6341 }
6342
6343 if (mFormats.size() != 0) {
6344 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6345 result.append(buffer);
6346 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006347 const char *formatStr = enumToString(sFormatNameToEnumTable,
6348 ARRAY_SIZE(sFormatNameToEnumTable),
6349 mFormats[i]);
6350 if (i == 0 && strcmp(formatStr, "") == 0) {
6351 snprintf(buffer, SIZE, "Dynamic");
6352 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006353 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006354 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006355 result.append(buffer);
6356 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6357 }
6358 result.append("\n");
6359 }
6360 write(fd, result.string(), result.size());
6361 if (mGains.size() != 0) {
6362 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6363 write(fd, buffer, strlen(buffer) + 1);
6364 result.append(buffer);
6365 for (size_t i = 0; i < mGains.size(); i++) {
6366 mGains[i]->dump(fd, spaces + 2, i);
6367 }
6368 }
6369}
6370
6371// --- AudioGain class implementation
6372
Eric Laurenta121f902014-06-03 13:32:54 -07006373AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006374{
Eric Laurenta121f902014-06-03 13:32:54 -07006375 mIndex = index;
6376 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006377 memset(&mGain, 0, sizeof(struct audio_gain));
6378}
6379
Eric Laurenta121f902014-06-03 13:32:54 -07006380void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6381{
6382 config->index = mIndex;
6383 config->mode = mGain.mode;
6384 config->channel_mask = mGain.channel_mask;
6385 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6386 config->values[0] = mGain.default_value;
6387 } else {
6388 uint32_t numValues;
6389 if (mUseInChannelMask) {
6390 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6391 } else {
6392 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6393 }
6394 for (size_t i = 0; i < numValues; i++) {
6395 config->values[i] = mGain.default_value;
6396 }
6397 }
6398 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6399 config->ramp_duration_ms = mGain.min_ramp_ms;
6400 }
6401}
6402
6403status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6404{
6405 if ((config->mode & ~mGain.mode) != 0) {
6406 return BAD_VALUE;
6407 }
6408 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6409 if ((config->values[0] < mGain.min_value) ||
6410 (config->values[0] > mGain.max_value)) {
6411 return BAD_VALUE;
6412 }
6413 } else {
6414 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6415 return BAD_VALUE;
6416 }
6417 uint32_t numValues;
6418 if (mUseInChannelMask) {
6419 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6420 } else {
6421 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6422 }
6423 for (size_t i = 0; i < numValues; i++) {
6424 if ((config->values[i] < mGain.min_value) ||
6425 (config->values[i] > mGain.max_value)) {
6426 return BAD_VALUE;
6427 }
6428 }
6429 }
6430 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6431 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6432 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6433 return BAD_VALUE;
6434 }
6435 }
6436 return NO_ERROR;
6437}
6438
Eric Laurent1afeecb2014-05-14 08:52:28 -07006439void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6440{
6441 const size_t SIZE = 256;
6442 char buffer[SIZE];
6443 String8 result;
6444
6445 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6446 result.append(buffer);
6447 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6448 result.append(buffer);
6449 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6450 result.append(buffer);
6451 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6452 result.append(buffer);
6453 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6454 result.append(buffer);
6455 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6456 result.append(buffer);
6457 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6458 result.append(buffer);
6459 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6460 result.append(buffer);
6461 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6462 result.append(buffer);
6463
6464 write(fd, result.string(), result.size());
6465}
6466
Eric Laurent1f2f2232014-06-02 12:01:23 -07006467// --- AudioPortConfig class implementation
6468
6469AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6470{
6471 mSamplingRate = 0;
6472 mChannelMask = AUDIO_CHANNEL_NONE;
6473 mFormat = AUDIO_FORMAT_INVALID;
6474 mGain.index = -1;
6475}
6476
Eric Laurenta121f902014-06-03 13:32:54 -07006477status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6478 const struct audio_port_config *config,
6479 struct audio_port_config *backupConfig)
6480{
6481 struct audio_port_config localBackupConfig;
6482 status_t status = NO_ERROR;
6483
6484 localBackupConfig.config_mask = config->config_mask;
6485 toAudioPortConfig(&localBackupConfig);
6486
Marco Nelissen961ec212014-08-25 15:58:39 -07006487 sp<AudioPort> audioport = getAudioPort();
6488 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006489 status = NO_INIT;
6490 goto exit;
6491 }
6492 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006493 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006494 if (status != NO_ERROR) {
6495 goto exit;
6496 }
6497 mSamplingRate = config->sample_rate;
6498 }
6499 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006500 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006501 if (status != NO_ERROR) {
6502 goto exit;
6503 }
6504 mChannelMask = config->channel_mask;
6505 }
6506 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006507 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006508 if (status != NO_ERROR) {
6509 goto exit;
6510 }
6511 mFormat = config->format;
6512 }
6513 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006514 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006515 if (status != NO_ERROR) {
6516 goto exit;
6517 }
6518 mGain = config->gain;
6519 }
6520
6521exit:
6522 if (status != NO_ERROR) {
6523 applyAudioPortConfig(&localBackupConfig);
6524 }
6525 if (backupConfig != NULL) {
6526 *backupConfig = localBackupConfig;
6527 }
6528 return status;
6529}
6530
Eric Laurent1f2f2232014-06-02 12:01:23 -07006531void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6532 struct audio_port_config *dstConfig,
6533 const struct audio_port_config *srcConfig) const
6534{
6535 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6536 dstConfig->sample_rate = mSamplingRate;
6537 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6538 dstConfig->sample_rate = srcConfig->sample_rate;
6539 }
6540 } else {
6541 dstConfig->sample_rate = 0;
6542 }
6543 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6544 dstConfig->channel_mask = mChannelMask;
6545 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6546 dstConfig->channel_mask = srcConfig->channel_mask;
6547 }
6548 } else {
6549 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6550 }
6551 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6552 dstConfig->format = mFormat;
6553 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6554 dstConfig->format = srcConfig->format;
6555 }
6556 } else {
6557 dstConfig->format = AUDIO_FORMAT_INVALID;
6558 }
6559 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6560 dstConfig->gain = mGain;
6561 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6562 dstConfig->gain = srcConfig->gain;
6563 }
6564 } else {
6565 dstConfig->gain.index = -1;
6566 }
6567 if (dstConfig->gain.index != -1) {
6568 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6569 } else {
6570 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6571 }
6572}
6573
Eric Laurent1c333e22014-05-20 10:48:17 -07006574// --- IOProfile class implementation
6575
Eric Laurent1afeecb2014-05-14 08:52:28 -07006576AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006577 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006578 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006579{
6580}
6581
Eric Laurente0720872014-03-11 09:30:41 -07006582AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006583{
6584}
6585
6586// checks if the IO profile is compatible with specified parameters.
6587// Sampling rate, format and channel mask must be specified in order to
6588// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006589bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006590 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006591 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006592 audio_format_t format,
6593 audio_channel_mask_t channelMask,
Eric Laurent5dbe4712014-09-19 19:04:57 -07006594 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07006595{
Glenn Kastencbd48022014-07-24 13:46:44 -07006596 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6597 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6598 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006599
Glenn Kastencbd48022014-07-24 13:46:44 -07006600 if ((mSupportedDevices.types() & device) != device) {
6601 return false;
6602 }
6603
6604 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006605 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006606 }
6607 uint32_t myUpdatedSamplingRate = samplingRate;
6608 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006609 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006610 }
6611 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6612 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006613 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006614 }
6615
6616 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6617 return false;
6618 }
6619
6620 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6621 checkExactChannelMask(channelMask) != NO_ERROR)) {
6622 return false;
6623 }
6624 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6625 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6626 return false;
6627 }
6628
6629 if (isPlaybackThread && (mFlags & flags) != flags) {
6630 return false;
6631 }
6632 // The only input flag that is allowed to be different is the fast flag.
6633 // An existing fast stream is compatible with a normal track request.
6634 // An existing normal stream is compatible with a fast track request,
6635 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07006636 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07006637 ~AUDIO_INPUT_FLAG_FAST)) {
6638 return false;
6639 }
6640
6641 if (updatedSamplingRate != NULL) {
6642 *updatedSamplingRate = myUpdatedSamplingRate;
6643 }
6644 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006645}
6646
Eric Laurente0720872014-03-11 09:30:41 -07006647void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006648{
6649 const size_t SIZE = 256;
6650 char buffer[SIZE];
6651 String8 result;
6652
Eric Laurent1afeecb2014-05-14 08:52:28 -07006653 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006654
Eric Laurente552edb2014-03-10 17:42:56 -07006655 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6656 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006657 snprintf(buffer, SIZE, " - devices:\n");
6658 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006659 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006660 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6661 mSupportedDevices[i]->dump(fd, 6, i);
6662 }
Eric Laurente552edb2014-03-10 17:42:56 -07006663}
6664
Eric Laurentd4692962014-05-05 18:13:44 -07006665void AudioPolicyManager::IOProfile::log()
6666{
6667 const size_t SIZE = 256;
6668 char buffer[SIZE];
6669 String8 result;
6670
6671 ALOGV(" - sampling rates: ");
6672 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6673 ALOGV(" %d", mSamplingRates[i]);
6674 }
6675
6676 ALOGV(" - channel masks: ");
6677 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6678 ALOGV(" 0x%04x", mChannelMasks[i]);
6679 }
6680
6681 ALOGV(" - formats: ");
6682 for (size_t i = 0; i < mFormats.size(); i++) {
6683 ALOGV(" 0x%08x", mFormats[i]);
6684 }
6685
6686 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6687 ALOGV(" - flags: 0x%04x\n", mFlags);
6688}
6689
6690
Eric Laurent3a4311c2014-03-17 12:00:47 -07006691// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006692
Eric Laurent1f2f2232014-06-02 12:01:23 -07006693
6694AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6695 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6696 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6697 AUDIO_PORT_ROLE_SOURCE,
6698 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006699 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006700{
Eric Laurenta121f902014-06-03 13:32:54 -07006701 if (mGains.size() > 0) {
6702 mGains[0]->getDefaultConfig(&mGain);
6703 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006704}
6705
Eric Laurent3a4311c2014-03-17 12:00:47 -07006706bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006707{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006708 // Devices are considered equal if they:
6709 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6710 // - have the same address or one device does not specify the address
6711 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006712 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006713 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006714 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006715 mChannelMask == other->mChannelMask);
6716}
6717
6718void AudioPolicyManager::DeviceVector::refreshTypes()
6719{
Eric Laurent1c333e22014-05-20 10:48:17 -07006720 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006721 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006722 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006723 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006724 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006725}
6726
6727ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6728{
6729 for(size_t i = 0; i < size(); i++) {
6730 if (item->equals(itemAt(i))) {
6731 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006732 }
6733 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006734 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006735}
6736
Eric Laurent3a4311c2014-03-17 12:00:47 -07006737ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006738{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006739 ssize_t ret = indexOf(item);
6740
6741 if (ret < 0) {
6742 ret = SortedVector::add(item);
6743 if (ret >= 0) {
6744 refreshTypes();
6745 }
6746 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006747 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006748 ret = -1;
6749 }
6750 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006751}
6752
Eric Laurent3a4311c2014-03-17 12:00:47 -07006753ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6754{
6755 size_t i;
6756 ssize_t ret = indexOf(item);
6757
6758 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006759 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006760 } else {
6761 ret = SortedVector::removeAt(ret);
6762 if (ret >= 0) {
6763 refreshTypes();
6764 }
6765 }
6766 return ret;
6767}
6768
6769void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6770{
6771 DeviceVector deviceList;
6772
6773 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6774 types &= ~role_bit;
6775
6776 while (types) {
6777 uint32_t i = 31 - __builtin_clz(types);
6778 uint32_t type = 1 << i;
6779 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006780 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006781 }
6782}
6783
Eric Laurent1afeecb2014-05-14 08:52:28 -07006784void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6785 const DeviceVector& declaredDevices)
6786{
6787 char *devName = strtok(name, "|");
6788 while (devName != NULL) {
6789 if (strlen(devName) != 0) {
6790 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6791 ARRAY_SIZE(sDeviceNameToEnumTable),
6792 devName);
6793 if (type != AUDIO_DEVICE_NONE) {
6794 add(new DeviceDescriptor(String8(""), type));
6795 } else {
6796 sp<DeviceDescriptor> deviceDesc =
6797 declaredDevices.getDeviceFromName(String8(devName));
6798 if (deviceDesc != 0) {
6799 add(deviceDesc);
6800 }
6801 }
6802 }
6803 devName = strtok(NULL, "|");
6804 }
6805}
6806
Eric Laurent1c333e22014-05-20 10:48:17 -07006807sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6808 audio_devices_t type, String8 address) const
6809{
6810 sp<DeviceDescriptor> device;
6811 for (size_t i = 0; i < size(); i++) {
6812 if (itemAt(i)->mDeviceType == type) {
6813 device = itemAt(i);
6814 if (itemAt(i)->mAddress = address) {
6815 break;
6816 }
6817 }
6818 }
6819 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6820 type, address.string(), device.get());
6821 return device;
6822}
6823
Eric Laurent6a94d692014-05-20 11:18:06 -07006824sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6825 audio_port_handle_t id) const
6826{
6827 sp<DeviceDescriptor> device;
6828 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006829 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006830 if (itemAt(i)->mId == id) {
6831 device = itemAt(i);
6832 break;
6833 }
6834 }
6835 return device;
6836}
6837
Eric Laurent1c333e22014-05-20 10:48:17 -07006838AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6839 audio_devices_t type) const
6840{
6841 DeviceVector devices;
6842 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6843 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6844 devices.add(itemAt(i));
6845 type &= ~itemAt(i)->mDeviceType;
6846 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6847 itemAt(i)->mDeviceType, itemAt(i).get());
6848 }
6849 }
6850 return devices;
6851}
6852
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006853AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6854 audio_devices_t type, String8 address) const
6855{
6856 DeviceVector devices;
6857 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6858 for (size_t i = 0; i < size(); i++) {
6859 //ALOGV(" at i=%d: device=%x, addr=%s",
6860 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6861 if (itemAt(i)->mDeviceType == type) {
6862 if (itemAt(i)->mAddress == address) {
6863 //ALOGV(" found matching address %s", address.string());
6864 devices.add(itemAt(i));
6865 }
6866 }
6867 }
6868 return devices;
6869}
6870
Eric Laurent1afeecb2014-05-14 08:52:28 -07006871sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6872 const String8& name) const
6873{
6874 sp<DeviceDescriptor> device;
6875 for (size_t i = 0; i < size(); i++) {
6876 if (itemAt(i)->mName == name) {
6877 device = itemAt(i);
6878 break;
6879 }
6880 }
6881 return device;
6882}
6883
Eric Laurent6a94d692014-05-20 11:18:06 -07006884void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6885 struct audio_port_config *dstConfig,
6886 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006887{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006888 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6889 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006890 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006891 }
6892
6893 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6894
Eric Laurent6a94d692014-05-20 11:18:06 -07006895 dstConfig->id = mId;
6896 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006897 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006898 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006899 dstConfig->ext.device.type = mDeviceType;
6900 dstConfig->ext.device.hw_module = mModule->mHandle;
6901 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006902}
6903
6904void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6905{
Eric Laurent83b88082014-06-20 18:31:16 -07006906 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006907 AudioPort::toAudioPort(port);
6908 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006909 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006910 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006911 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006912 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6913}
6914
Eric Laurent1afeecb2014-05-14 08:52:28 -07006915status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006916{
6917 const size_t SIZE = 256;
6918 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006919 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006920
Eric Laurent1afeecb2014-05-14 08:52:28 -07006921 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6922 result.append(buffer);
6923 if (mId != 0) {
6924 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6925 result.append(buffer);
6926 }
6927 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6928 enumToString(sDeviceNameToEnumTable,
6929 ARRAY_SIZE(sDeviceNameToEnumTable),
6930 mDeviceType));
6931 result.append(buffer);
6932 if (mAddress.size() != 0) {
6933 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6934 result.append(buffer);
6935 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006936 write(fd, result.string(), result.size());
6937 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006938
6939 return NO_ERROR;
6940}
6941
Eric Laurent4d416952014-08-10 14:07:09 -07006942status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
6943{
6944 const size_t SIZE = 256;
6945 char buffer[SIZE];
6946 String8 result;
6947
6948
6949 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
6950 result.append(buffer);
6951 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
6952 result.append(buffer);
6953 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
6954 result.append(buffer);
6955 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
6956 result.append(buffer);
6957 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
6958 result.append(buffer);
6959 for (size_t i = 0; i < mPatch.num_sources; i++) {
6960 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
6961 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6962 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
6963 ARRAY_SIZE(sDeviceNameToEnumTable),
6964 mPatch.sources[i].ext.device.type));
6965 } else {
6966 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6967 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
6968 }
6969 result.append(buffer);
6970 }
6971 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
6972 result.append(buffer);
6973 for (size_t i = 0; i < mPatch.num_sinks; i++) {
6974 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
6975 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6976 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
6977 ARRAY_SIZE(sDeviceNameToEnumTable),
6978 mPatch.sinks[i].ext.device.type));
6979 } else {
6980 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6981 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
6982 }
6983 result.append(buffer);
6984 }
6985
6986 write(fd, result.string(), result.size());
6987 return NO_ERROR;
6988}
Eric Laurent3a4311c2014-03-17 12:00:47 -07006989
6990// --- audio_policy.conf file parsing
6991
Eric Laurent5dbe4712014-09-19 19:04:57 -07006992uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006993{
6994 uint32_t flag = 0;
6995
6996 // it is OK to cast name to non const here as we are not going to use it after
6997 // strtok() modifies it
6998 char *flagName = strtok(name, "|");
6999 while (flagName != NULL) {
7000 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007001 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7002 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007003 flagName);
7004 }
7005 flagName = strtok(NULL, "|");
7006 }
7007 //force direct flag if offload flag is set: offloading implies a direct output stream
7008 // and all common behaviors are driven by checking only the direct flag
7009 // this should normally be set appropriately in the policy configuration file
7010 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7011 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7012 }
7013
Eric Laurent5dbe4712014-09-19 19:04:57 -07007014 return flag;
7015}
7016
7017uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7018{
7019 uint32_t flag = 0;
7020
7021 // it is OK to cast name to non const here as we are not going to use it after
7022 // strtok() modifies it
7023 char *flagName = strtok(name, "|");
7024 while (flagName != NULL) {
7025 if (strlen(flagName) != 0) {
7026 flag |= stringToEnum(sInputFlagNameToEnumTable,
7027 ARRAY_SIZE(sInputFlagNameToEnumTable),
7028 flagName);
7029 }
7030 flagName = strtok(NULL, "|");
7031 }
7032 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007033}
7034
Eric Laurente0720872014-03-11 09:30:41 -07007035audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007036{
7037 uint32_t device = 0;
7038
7039 char *devName = strtok(name, "|");
7040 while (devName != NULL) {
7041 if (strlen(devName) != 0) {
7042 device |= stringToEnum(sDeviceNameToEnumTable,
7043 ARRAY_SIZE(sDeviceNameToEnumTable),
7044 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007045 }
Eric Laurente552edb2014-03-10 17:42:56 -07007046 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007047 }
Eric Laurente552edb2014-03-10 17:42:56 -07007048 return device;
7049}
7050
Eric Laurente0720872014-03-11 09:30:41 -07007051void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007052{
Eric Laurente552edb2014-03-10 17:42:56 -07007053 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007054 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007055 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007056
Eric Laurent1afeecb2014-05-14 08:52:28 -07007057 node = config_find(root, DEVICES_TAG);
7058 if (node != NULL) {
7059 node = node->first_child;
7060 while (node) {
7061 ALOGV("loadHwModule() loading device %s", node->name);
7062 status_t tmpStatus = module->loadDevice(node);
7063 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7064 status = tmpStatus;
7065 }
7066 node = node->next;
7067 }
7068 }
7069 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007070 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007071 node = node->first_child;
7072 while (node) {
7073 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007074 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007075 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7076 status = tmpStatus;
7077 }
7078 node = node->next;
7079 }
7080 }
7081 node = config_find(root, INPUTS_TAG);
7082 if (node != NULL) {
7083 node = node->first_child;
7084 while (node) {
7085 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007086 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007087 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7088 status = tmpStatus;
7089 }
7090 node = node->next;
7091 }
7092 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007093 loadGlobalConfig(root, module);
7094
Eric Laurente552edb2014-03-10 17:42:56 -07007095 if (status == NO_ERROR) {
7096 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007097 }
7098}
7099
Eric Laurente0720872014-03-11 09:30:41 -07007100void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007101{
7102 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7103 if (node == NULL) {
7104 return;
7105 }
7106
7107 node = node->first_child;
7108 while (node) {
7109 ALOGV("loadHwModules() loading module %s", node->name);
7110 loadHwModule(node);
7111 node = node->next;
7112 }
7113}
7114
Eric Laurent1f2f2232014-06-02 12:01:23 -07007115void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007116{
7117 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007118
Eric Laurente552edb2014-03-10 17:42:56 -07007119 if (node == NULL) {
7120 return;
7121 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007122 DeviceVector declaredDevices;
7123 if (module != NULL) {
7124 declaredDevices = module->mDeclaredDevices;
7125 }
7126
Eric Laurente552edb2014-03-10 17:42:56 -07007127 node = node->first_child;
7128 while (node) {
7129 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007130 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7131 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007132 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7133 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007134 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007135 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007136 ARRAY_SIZE(sDeviceNameToEnumTable),
7137 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007138 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007139 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007140 } else {
7141 ALOGW("loadGlobalConfig() default device not specified");
7142 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007143 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007144 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007145 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7146 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007147 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007148 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7149 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7150 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007151 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7152 uint32_t major, minor;
7153 sscanf((char *)node->value, "%u.%u", &major, &minor);
7154 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7155 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7156 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007157 }
7158 node = node->next;
7159 }
7160}
7161
Eric Laurente0720872014-03-11 09:30:41 -07007162status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007163{
7164 cnode *root;
7165 char *data;
7166
7167 data = (char *)load_file(path, NULL);
7168 if (data == NULL) {
7169 return -ENODEV;
7170 }
7171 root = config_node("", "");
7172 config_load(root, data);
7173
Eric Laurente552edb2014-03-10 17:42:56 -07007174 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007175 // legacy audio_policy.conf files have one global_configuration section
7176 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007177 config_free(root);
7178 free(root);
7179 free(data);
7180
7181 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7182
7183 return NO_ERROR;
7184}
7185
Eric Laurente0720872014-03-11 09:30:41 -07007186void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007187{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007188 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007189 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007190 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7191 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007192 mAvailableOutputDevices.add(mDefaultOutputDevice);
7193 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007194
7195 module = new HwModule("primary");
7196
Eric Laurent1afeecb2014-05-14 08:52:28 -07007197 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007198 profile->mSamplingRates.add(44100);
7199 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7200 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007201 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007202 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7203 module->mOutputProfiles.add(profile);
7204
Eric Laurent1afeecb2014-05-14 08:52:28 -07007205 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007206 profile->mSamplingRates.add(8000);
7207 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7208 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007209 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007210 module->mInputProfiles.add(profile);
7211
7212 mHwModules.add(module);
7213}
7214
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007215audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7216{
7217 // flags to stream type mapping
7218 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7219 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7220 }
7221 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7222 return AUDIO_STREAM_BLUETOOTH_SCO;
7223 }
7224
7225 // usage to stream type mapping
7226 switch (attr->usage) {
7227 case AUDIO_USAGE_MEDIA:
7228 case AUDIO_USAGE_GAME:
7229 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7230 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7231 return AUDIO_STREAM_MUSIC;
7232 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7233 return AUDIO_STREAM_SYSTEM;
7234 case AUDIO_USAGE_VOICE_COMMUNICATION:
7235 return AUDIO_STREAM_VOICE_CALL;
7236
7237 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7238 return AUDIO_STREAM_DTMF;
7239
7240 case AUDIO_USAGE_ALARM:
7241 return AUDIO_STREAM_ALARM;
7242 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7243 return AUDIO_STREAM_RING;
7244
7245 case AUDIO_USAGE_NOTIFICATION:
7246 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7247 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7248 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7249 case AUDIO_USAGE_NOTIFICATION_EVENT:
7250 return AUDIO_STREAM_NOTIFICATION;
7251
7252 case AUDIO_USAGE_UNKNOWN:
7253 default:
7254 return AUDIO_STREAM_MUSIC;
7255 }
7256}
Eric Laurente552edb2014-03-10 17:42:56 -07007257}; // namespace android