blob: c4375515dc5126dcec358a1709fdd4e1931a55d9 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
Hochi Huang327cb702014-09-21 09:47:31 +080029#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX|AUDIO_DEVICE_IN_FM_TUNER)
Eric Laurente552edb2014-03-10 17:42:56 -070030// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -070033// A device mask for all audio input and output devices where matching inputs/outputs on device
34// type alone is not enough: the address must match too
35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36 AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
Eric Laurente552edb2014-03-10 17:42:56 -070037
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070039#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070040
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070046#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070047#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070048#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
52// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070053// Definitions for audio_policy.conf file parsing
54// ----------------------------------------------------------------------------
55
56struct StringToEnum {
57 const char *name;
58 uint32_t value;
59};
60
61#define STRING_TO_ENUM(string) { #string, string }
62#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
63
64const StringToEnum sDeviceNameToEnumTable[] = {
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
Jon Eklund11c9fb12014-06-23 14:47:03 -050067 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER_SAFE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070068 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070079 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070086 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
87 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
90 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070091 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050092 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070093 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700101 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
105 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700106 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700107 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
108 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
110 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700111 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900112 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700113};
114
Eric Laurent5dbe4712014-09-19 19:04:57 -0700115const StringToEnum sOutputFlagNameToEnumTable[] = {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700116 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
Eric Laurent93c3d412014-08-01 14:48:35 -0700122 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700123};
124
Eric Laurent5dbe4712014-09-19 19:04:57 -0700125const StringToEnum sInputFlagNameToEnumTable[] = {
126 STRING_TO_ENUM(AUDIO_INPUT_FLAG_FAST),
127 STRING_TO_ENUM(AUDIO_INPUT_FLAG_HW_HOTWORD),
128};
129
Eric Laurent3a4311c2014-03-17 12:00:47 -0700130const StringToEnum sFormatNameToEnumTable[] = {
131 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
132 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
133 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
134 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
135 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
136 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
137 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
138 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530139 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
143 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
144 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
145 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
146 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
147 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
148 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700149 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700150 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
151 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
152 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
153 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
154 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700155};
156
157const StringToEnum sOutChannelsNameToEnumTable[] = {
158 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
159 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700160 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700161 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
162 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
163};
164
165const StringToEnum sInChannelsNameToEnumTable[] = {
166 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
167 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
168 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
169};
170
Eric Laurent1afeecb2014-05-14 08:52:28 -0700171const StringToEnum sGainModeNameToEnumTable[] = {
172 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
173 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
174 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
175};
176
Eric Laurent3a4311c2014-03-17 12:00:47 -0700177
178uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
179 size_t size,
180 const char *name)
181{
182 for (size_t i = 0; i < size; i++) {
183 if (strcmp(table[i].name, name) == 0) {
184 ALOGV("stringToEnum() found %s", table[i].name);
185 return table[i].value;
186 }
187 }
188 return 0;
189}
190
191const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
192 size_t size,
193 uint32_t value)
194{
195 for (size_t i = 0; i < size; i++) {
196 if (table[i].value == value) {
197 return table[i].name;
198 }
199 }
200 return "";
201}
202
203bool AudioPolicyManager::stringToBool(const char *value)
204{
205 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
206}
207
208
209// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700210// AudioPolicyInterface implementation
211// ----------------------------------------------------------------------------
212
213
Eric Laurente0720872014-03-11 09:30:41 -0700214status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700215 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700216 const char *device_address)
217{
Eric Laurent22226012014-08-01 17:00:54 -0700218 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
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 &&
Hochi Huang327cb702014-09-21 09:47:31 +0800710 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
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 }
Hochi Huang327cb702014-09-21 09:47:31 +08004161 if ((device2 == AUDIO_DEVICE_NONE) &&
4162 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4163 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4164 }
Eric Laurente552edb2014-03-10 17:42:56 -07004165 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004166 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004167 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004168 if ((device2 == AUDIO_DEVICE_NONE)) {
4169 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4170 }
Eric Laurente552edb2014-03-10 17:42:56 -07004171 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004172 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004173 }
4174 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004175 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004176 }
4177 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004178 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004179 }
4180 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004181 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004182 }
4183 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4184 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004185 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004186 }
4187 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004188 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004189 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004190 }
4191 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004192 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004193 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004194 int device3 = AUDIO_DEVICE_NONE;
4195 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004196 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004197 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4198 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004199 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004200 }
Eric Laurente552edb2014-03-10 17:42:56 -07004201
Jungshik Jang839e4f32014-06-26 17:23:40 +09004202 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004203 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4204 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4205 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004206
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004207 // If hdmi system audio mode is on, remove speaker out of output list.
4208 if ((strategy == STRATEGY_MEDIA) &&
4209 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4210 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4211 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4212 }
4213
Eric Laurente552edb2014-03-10 17:42:56 -07004214 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004215 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004216 if (device == AUDIO_DEVICE_NONE) {
4217 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4218 }
4219 } break;
4220
4221 default:
4222 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4223 break;
4224 }
4225
4226 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4227 return device;
4228}
4229
Eric Laurente0720872014-03-11 09:30:41 -07004230void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004231{
4232 for (int i = 0; i < NUM_STRATEGIES; i++) {
4233 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4234 }
4235 mPreviousOutputs = mOutputs;
4236}
4237
Eric Laurent1f2f2232014-06-02 12:01:23 -07004238uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004239 audio_devices_t prevDevice,
4240 uint32_t delayMs)
4241{
4242 // mute/unmute strategies using an incompatible device combination
4243 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4244 // if unmuting, unmute only after the specified delay
4245 if (outputDesc->isDuplicated()) {
4246 return 0;
4247 }
4248
4249 uint32_t muteWaitMs = 0;
4250 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004251 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004252
4253 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4254 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4255 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4256 bool doMute = false;
4257
4258 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4259 doMute = true;
4260 outputDesc->mStrategyMutedByDevice[i] = true;
4261 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4262 doMute = true;
4263 outputDesc->mStrategyMutedByDevice[i] = false;
4264 }
Eric Laurent99401132014-05-07 19:48:15 -07004265 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004266 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004267 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004268 // skip output if it does not share any device with current output
4269 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4270 == AUDIO_DEVICE_NONE) {
4271 continue;
4272 }
4273 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4274 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4275 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4276 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4277 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004278 if (mute) {
4279 // FIXME: should not need to double latency if volume could be applied
4280 // immediately by the audioflinger mixer. We must account for the delay
4281 // between now and the next time the audioflinger thread for this output
4282 // will process a buffer (which corresponds to one buffer size,
4283 // usually 1/2 or 1/4 of the latency).
4284 if (muteWaitMs < desc->latency() * 2) {
4285 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004286 }
4287 }
4288 }
4289 }
4290 }
4291 }
4292
Eric Laurent99401132014-05-07 19:48:15 -07004293 // temporary mute output if device selection changes to avoid volume bursts due to
4294 // different per device volumes
4295 if (outputDesc->isActive() && (device != prevDevice)) {
4296 if (muteWaitMs < outputDesc->latency() * 2) {
4297 muteWaitMs = outputDesc->latency() * 2;
4298 }
4299 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4300 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004301 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004302 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004303 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004304 muteWaitMs *2, device);
4305 }
4306 }
4307 }
4308
Eric Laurente552edb2014-03-10 17:42:56 -07004309 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4310 if (muteWaitMs > delayMs) {
4311 muteWaitMs -= delayMs;
4312 usleep(muteWaitMs * 1000);
4313 return muteWaitMs;
4314 }
4315 return 0;
4316}
4317
Eric Laurente0720872014-03-11 09:30:41 -07004318uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004319 audio_devices_t device,
4320 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004321 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004322 audio_patch_handle_t *patchHandle,
4323 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004324{
4325 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004326 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004327 AudioParameter param;
4328 uint32_t muteWaitMs;
4329
4330 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004331 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4332 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004333 return muteWaitMs;
4334 }
4335 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4336 // output profile
4337 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004338 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004339 return 0;
4340 }
4341
4342 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004343 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004344
4345 audio_devices_t prevDevice = outputDesc->mDevice;
4346
4347 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4348
4349 if (device != AUDIO_DEVICE_NONE) {
4350 outputDesc->mDevice = device;
4351 }
4352 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4353
4354 // Do not change the routing if:
4355 // - the requested device is AUDIO_DEVICE_NONE
4356 // - the requested device is the same as current device and force is not specified.
4357 // Doing this check here allows the caller to call setOutputDevice() without conditions
4358 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
4359 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
4360 return muteWaitMs;
4361 }
4362
4363 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004364
Eric Laurente552edb2014-03-10 17:42:56 -07004365 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004366 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004367 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004368 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004369 DeviceVector deviceList = (address == NULL) ?
4370 mAvailableOutputDevices.getDevicesFromType(device)
4371 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004372 if (!deviceList.isEmpty()) {
4373 struct audio_patch patch;
4374 outputDesc->toAudioPortConfig(&patch.sources[0]);
4375 patch.num_sources = 1;
4376 patch.num_sinks = 0;
4377 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4378 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004379 patch.num_sinks++;
4380 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004381 ssize_t index;
4382 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4383 index = mAudioPatches.indexOfKey(*patchHandle);
4384 } else {
4385 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4386 }
4387 sp< AudioPatch> patchDesc;
4388 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4389 if (index >= 0) {
4390 patchDesc = mAudioPatches.valueAt(index);
4391 afPatchHandle = patchDesc->mAfPatchHandle;
4392 }
4393
Eric Laurent1c333e22014-05-20 10:48:17 -07004394 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004395 &afPatchHandle,
4396 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004397 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4398 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004399 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004400 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004401 if (index < 0) {
4402 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4403 &patch, mUidCached);
4404 addAudioPatch(patchDesc->mHandle, patchDesc);
4405 } else {
4406 patchDesc->mPatch = patch;
4407 }
4408 patchDesc->mAfPatchHandle = afPatchHandle;
4409 patchDesc->mUid = mUidCached;
4410 if (patchHandle) {
4411 *patchHandle = patchDesc->mHandle;
4412 }
4413 outputDesc->mPatchHandle = patchDesc->mHandle;
4414 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004415 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004416 }
4417 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004418
4419 // inform all input as well
4420 for (size_t i = 0; i < mInputs.size(); i++) {
4421 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
4422 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
4423 AudioParameter inputCmd = AudioParameter();
4424 ALOGV("%s: inform input %d of device:%d", __func__,
4425 inputDescriptor->mIoHandle, device);
4426 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4427 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4428 inputCmd.toString(),
4429 delayMs);
4430 }
4431 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004432 }
Eric Laurente552edb2014-03-10 17:42:56 -07004433
4434 // update stream volumes according to new device
4435 applyStreamVolumes(output, device, delayMs);
4436
4437 return muteWaitMs;
4438}
4439
Eric Laurent1c333e22014-05-20 10:48:17 -07004440status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07004441 int delayMs,
4442 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004443{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004444 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004445 ssize_t index;
4446 if (patchHandle) {
4447 index = mAudioPatches.indexOfKey(*patchHandle);
4448 } else {
4449 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4450 }
4451 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004452 return INVALID_OPERATION;
4453 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004454 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4455 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004456 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4457 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004458 removeAudioPatch(patchDesc->mHandle);
4459 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004460 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004461 return status;
4462}
4463
4464status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4465 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004466 bool force,
4467 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004468{
4469 status_t status = NO_ERROR;
4470
Eric Laurent1f2f2232014-06-02 12:01:23 -07004471 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004472 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4473 inputDesc->mDevice = device;
4474
4475 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4476 if (!deviceList.isEmpty()) {
4477 struct audio_patch patch;
4478 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004479 // AUDIO_SOURCE_HOTWORD is for internal use only:
4480 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004481 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4482 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004483 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4484 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004485 patch.num_sinks = 1;
4486 //only one input device for now
4487 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004488 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004489 ssize_t index;
4490 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4491 index = mAudioPatches.indexOfKey(*patchHandle);
4492 } else {
4493 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4494 }
4495 sp< AudioPatch> patchDesc;
4496 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4497 if (index >= 0) {
4498 patchDesc = mAudioPatches.valueAt(index);
4499 afPatchHandle = patchDesc->mAfPatchHandle;
4500 }
4501
Eric Laurent1c333e22014-05-20 10:48:17 -07004502 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004503 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004504 0);
4505 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004506 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004507 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004508 if (index < 0) {
4509 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4510 &patch, mUidCached);
4511 addAudioPatch(patchDesc->mHandle, patchDesc);
4512 } else {
4513 patchDesc->mPatch = patch;
4514 }
4515 patchDesc->mAfPatchHandle = afPatchHandle;
4516 patchDesc->mUid = mUidCached;
4517 if (patchHandle) {
4518 *patchHandle = patchDesc->mHandle;
4519 }
4520 inputDesc->mPatchHandle = patchDesc->mHandle;
4521 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004522 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004523 }
4524 }
4525 }
4526 return status;
4527}
4528
Eric Laurent6a94d692014-05-20 11:18:06 -07004529status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4530 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004531{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004532 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004533 ssize_t index;
4534 if (patchHandle) {
4535 index = mAudioPatches.indexOfKey(*patchHandle);
4536 } else {
4537 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4538 }
4539 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004540 return INVALID_OPERATION;
4541 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004542 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4543 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004544 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4545 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004546 removeAudioPatch(patchDesc->mHandle);
4547 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004548 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004549 return status;
4550}
4551
4552sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004553 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004554 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004555 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004556 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004557{
4558 // Choose an input profile based on the requested capture parameters: select the first available
4559 // profile supporting all requested parameters.
4560
4561 for (size_t i = 0; i < mHwModules.size(); i++)
4562 {
4563 if (mHwModules[i]->mHandle == 0) {
4564 continue;
4565 }
4566 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4567 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004568 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004569 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004570 if (profile->isCompatibleProfile(device, samplingRate,
4571 &samplingRate /*updatedSamplingRate*/,
4572 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004573 return profile;
4574 }
4575 }
4576 }
4577 return NULL;
4578}
4579
Eric Laurente0720872014-03-11 09:30:41 -07004580audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004581{
4582 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004583 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4584 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004585 switch (inputSource) {
4586 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004587 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004588 device = AUDIO_DEVICE_IN_VOICE_CALL;
4589 break;
4590 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004591 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004592
4593 case AUDIO_SOURCE_DEFAULT:
4594 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004595 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4596 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004597 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4598 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4599 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4600 device = AUDIO_DEVICE_IN_USB_DEVICE;
4601 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4602 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004603 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07004604 break;
4605
4606 case AUDIO_SOURCE_VOICE_COMMUNICATION:
4607 // Allow only use of devices on primary input if in call and HAL does not support routing
4608 // to voice call path.
4609 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
4610 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
4611 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
4612 }
4613
4614 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4615 case AUDIO_POLICY_FORCE_BT_SCO:
4616 // if SCO device is requested but no SCO device is available, fall back to default case
4617 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4618 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4619 break;
4620 }
4621 // FALL THROUGH
4622
4623 default: // FORCE_NONE
4624 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4625 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4626 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4627 device = AUDIO_DEVICE_IN_USB_DEVICE;
4628 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4629 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4630 }
4631 break;
4632
4633 case AUDIO_POLICY_FORCE_SPEAKER:
4634 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4635 device = AUDIO_DEVICE_IN_BACK_MIC;
4636 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4637 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4638 }
4639 break;
4640 }
4641 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07004642
Eric Laurente552edb2014-03-10 17:42:56 -07004643 case AUDIO_SOURCE_VOICE_RECOGNITION:
4644 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07004645 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004646 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004647 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004648 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004649 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004650 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4651 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004652 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004653 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4654 }
4655 break;
4656 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004657 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004658 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004659 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004660 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4661 }
4662 break;
4663 case AUDIO_SOURCE_VOICE_DOWNLINK:
4664 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004665 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004666 device = AUDIO_DEVICE_IN_VOICE_CALL;
4667 }
4668 break;
4669 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004670 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004671 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4672 }
4673 break;
Hochi Huang327cb702014-09-21 09:47:31 +08004674 case AUDIO_SOURCE_FM_TUNER:
4675 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
4676 device = AUDIO_DEVICE_IN_FM_TUNER;
4677 }
4678 break;
Eric Laurente552edb2014-03-10 17:42:56 -07004679 default:
4680 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4681 break;
4682 }
4683 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4684 return device;
4685}
4686
Eric Laurente0720872014-03-11 09:30:41 -07004687bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004688{
4689 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4690 device &= ~AUDIO_DEVICE_BIT_IN;
4691 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4692 return true;
4693 }
4694 return false;
4695}
4696
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004697bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4698 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4699}
4700
Eric Laurente0720872014-03-11 09:30:41 -07004701audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004702{
4703 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004704 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004705 if ((input_descriptor->mRefCount > 0)
4706 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4707 return mInputs.keyAt(i);
4708 }
4709 }
4710 return 0;
4711}
4712
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004713uint32_t AudioPolicyManager::activeInputsCount() const
4714{
4715 uint32_t count = 0;
4716 for (size_t i = 0; i < mInputs.size(); i++) {
4717 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
4718 if (desc->mRefCount > 0) {
4719 return count++;
4720 }
4721 }
4722 return count;
4723}
4724
Eric Laurente552edb2014-03-10 17:42:56 -07004725
Eric Laurente0720872014-03-11 09:30:41 -07004726audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004727{
4728 if (device == AUDIO_DEVICE_NONE) {
4729 // this happens when forcing a route update and no track is active on an output.
4730 // In this case the returned category is not important.
4731 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004732 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004733 // Multiple device selection is either:
4734 // - speaker + one other device: give priority to speaker in this case.
4735 // - one A2DP device + another device: happens with duplicated output. In this case
4736 // retain the device on the A2DP output as the other must not correspond to an active
4737 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09004738 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07004739 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4740 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09004741 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
4742 device = AUDIO_DEVICE_OUT_HDMI_ARC;
4743 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
4744 device = AUDIO_DEVICE_OUT_AUX_LINE;
4745 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
4746 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07004747 } else {
4748 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4749 }
4750 }
4751
Jon Eklund11c9fb12014-06-23 14:47:03 -05004752 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
4753 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
4754 device = AUDIO_DEVICE_OUT_SPEAKER;
4755
Eric Laurent3b73df72014-03-11 09:06:29 -07004756 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004757 "getDeviceForVolume() invalid device combination: %08x",
4758 device);
4759
4760 return device;
4761}
4762
Eric Laurente0720872014-03-11 09:30:41 -07004763AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004764{
4765 switch(getDeviceForVolume(device)) {
4766 case AUDIO_DEVICE_OUT_EARPIECE:
4767 return DEVICE_CATEGORY_EARPIECE;
4768 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4769 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4770 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4771 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4772 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4773 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4774 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05004775 case AUDIO_DEVICE_OUT_LINE:
4776 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4777 /*USB? Remote submix?*/
4778 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07004779 case AUDIO_DEVICE_OUT_SPEAKER:
4780 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4781 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004782 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4783 case AUDIO_DEVICE_OUT_USB_DEVICE:
4784 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4785 default:
4786 return DEVICE_CATEGORY_SPEAKER;
4787 }
4788}
4789
Eric Laurente0720872014-03-11 09:30:41 -07004790float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004791 int indexInUi)
4792{
4793 device_category deviceCategory = getDeviceCategory(device);
4794 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4795
4796 // the volume index in the UI is relative to the min and max volume indices for this stream type
4797 int nbSteps = 1 + curve[VOLMAX].mIndex -
4798 curve[VOLMIN].mIndex;
4799 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4800 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4801
4802 // find what part of the curve this index volume belongs to, or if it's out of bounds
4803 int segment = 0;
4804 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4805 return 0.0f;
4806 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4807 segment = 0;
4808 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4809 segment = 1;
4810 } else if (volIdx <= curve[VOLMAX].mIndex) {
4811 segment = 2;
4812 } else { // out of bounds
4813 return 1.0f;
4814 }
4815
4816 // linear interpolation in the attenuation table in dB
4817 float decibels = curve[segment].mDBAttenuation +
4818 ((float)(volIdx - curve[segment].mIndex)) *
4819 ( (curve[segment+1].mDBAttenuation -
4820 curve[segment].mDBAttenuation) /
4821 ((float)(curve[segment+1].mIndex -
4822 curve[segment].mIndex)) );
4823
4824 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4825
4826 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4827 curve[segment].mIndex, volIdx,
4828 curve[segment+1].mIndex,
4829 curve[segment].mDBAttenuation,
4830 decibels,
4831 curve[segment+1].mDBAttenuation,
4832 amplification);
4833
4834 return amplification;
4835}
4836
Eric Laurente0720872014-03-11 09:30:41 -07004837const AudioPolicyManager::VolumeCurvePoint
4838 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004839 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4840};
4841
Eric Laurente0720872014-03-11 09:30:41 -07004842const AudioPolicyManager::VolumeCurvePoint
4843 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004844 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4845};
4846
Eric Laurente0720872014-03-11 09:30:41 -07004847const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05004848 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4849 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4850};
4851
4852const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004853 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004854 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4855};
4856
Eric Laurente0720872014-03-11 09:30:41 -07004857const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004858 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004859 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004860};
4861
4862const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004863 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004864 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4865};
4866
Eric Laurente0720872014-03-11 09:30:41 -07004867const AudioPolicyManager::VolumeCurvePoint
4868 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004869 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4870};
4871
4872// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4873// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4874// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4875// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4876
Eric Laurente0720872014-03-11 09:30:41 -07004877const AudioPolicyManager::VolumeCurvePoint
4878 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004879 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4880};
4881
Eric Laurente0720872014-03-11 09:30:41 -07004882const AudioPolicyManager::VolumeCurvePoint
4883 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004884 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4885};
4886
Eric Laurente0720872014-03-11 09:30:41 -07004887const AudioPolicyManager::VolumeCurvePoint
4888 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004889 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4890};
4891
Eric Laurente0720872014-03-11 09:30:41 -07004892const AudioPolicyManager::VolumeCurvePoint
4893 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004894 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4895};
4896
Eric Laurente0720872014-03-11 09:30:41 -07004897const AudioPolicyManager::VolumeCurvePoint
4898 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004899 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4900};
4901
Eric Laurente0720872014-03-11 09:30:41 -07004902const AudioPolicyManager::VolumeCurvePoint
4903 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4904 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004905 { // AUDIO_STREAM_VOICE_CALL
4906 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4907 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004908 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4909 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004910 },
4911 { // AUDIO_STREAM_SYSTEM
4912 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4913 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004914 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4915 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004916 },
4917 { // AUDIO_STREAM_RING
4918 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4919 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004920 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4921 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004922 },
4923 { // AUDIO_STREAM_MUSIC
4924 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4925 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004926 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4927 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004928 },
4929 { // AUDIO_STREAM_ALARM
4930 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4931 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004932 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4933 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004934 },
4935 { // AUDIO_STREAM_NOTIFICATION
4936 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4937 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004938 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4939 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004940 },
4941 { // AUDIO_STREAM_BLUETOOTH_SCO
4942 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4943 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004944 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4945 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004946 },
4947 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4948 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4949 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004950 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4951 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004952 },
4953 { // AUDIO_STREAM_DTMF
4954 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4955 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004956 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4957 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004958 },
4959 { // AUDIO_STREAM_TTS
4960 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4961 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05004962 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4963 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07004964 },
4965};
4966
Eric Laurente0720872014-03-11 09:30:41 -07004967void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004968{
4969 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4970 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4971 mStreams[i].mVolumeCurve[j] =
4972 sVolumeProfiles[i][j];
4973 }
4974 }
4975
4976 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4977 if (mSpeakerDrcEnabled) {
4978 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4979 sDefaultSystemVolumeCurveDrc;
4980 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4981 sSpeakerSonificationVolumeCurveDrc;
4982 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4983 sSpeakerSonificationVolumeCurveDrc;
4984 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4985 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004986 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4987 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004988 }
4989}
4990
Eric Laurente0720872014-03-11 09:30:41 -07004991float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004992 int index,
4993 audio_io_handle_t output,
4994 audio_devices_t device)
4995{
4996 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004997 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004998 StreamDescriptor &streamDesc = mStreams[stream];
4999
5000 if (device == AUDIO_DEVICE_NONE) {
5001 device = outputDesc->device();
5002 }
5003
Eric Laurente552edb2014-03-10 17:42:56 -07005004 volume = volIndexToAmpl(device, streamDesc, index);
5005
5006 // if a headset is connected, apply the following rules to ring tones and notifications
5007 // to avoid sound level bursts in user's ears:
5008 // - always attenuate ring tones and notifications volume by 6dB
5009 // - if music is playing, always limit the volume to current music volume,
5010 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005011 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005012 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5013 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5014 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5015 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5016 ((stream_strategy == STRATEGY_SONIFICATION)
5017 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005018 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005019 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005020 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005021 streamDesc.mCanBeMuted) {
5022 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5023 // when the phone is ringing we must consider that music could have been paused just before
5024 // by the music application and behave as if music was active if the last music track was
5025 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005026 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005027 mLimitRingtoneVolume) {
5028 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005029 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5030 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005031 output,
5032 musicDevice);
5033 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5034 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5035 if (volume > minVol) {
5036 volume = minVol;
5037 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5038 }
5039 }
5040 }
5041
5042 return volume;
5043}
5044
Eric Laurente0720872014-03-11 09:30:41 -07005045status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005046 int index,
5047 audio_io_handle_t output,
5048 audio_devices_t device,
5049 int delayMs,
5050 bool force)
5051{
5052
5053 // do not change actual stream volume if the stream is muted
5054 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5055 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5056 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5057 return NO_ERROR;
5058 }
5059
5060 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005061 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5062 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5063 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5064 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005065 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005066 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005067 return INVALID_OPERATION;
5068 }
5069
5070 float volume = computeVolume(stream, index, output, device);
5071 // We actually change the volume if:
5072 // - the float value returned by computeVolume() changed
5073 // - the force flag is set
5074 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5075 force) {
5076 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5077 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5078 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5079 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005080 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5081 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005082 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005083 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005084 }
5085
Eric Laurent3b73df72014-03-11 09:06:29 -07005086 if (stream == AUDIO_STREAM_VOICE_CALL ||
5087 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005088 float voiceVolume;
5089 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005090 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005091 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5092 } else {
5093 voiceVolume = 1.0;
5094 }
5095
5096 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5097 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5098 mLastVoiceVolume = voiceVolume;
5099 }
5100 }
5101
5102 return NO_ERROR;
5103}
5104
Eric Laurente0720872014-03-11 09:30:41 -07005105void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005106 audio_devices_t device,
5107 int delayMs,
5108 bool force)
5109{
5110 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5111
Eric Laurent3b73df72014-03-11 09:06:29 -07005112 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5113 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005114 mStreams[stream].getVolumeIndex(device),
5115 output,
5116 device,
5117 delayMs,
5118 force);
5119 }
5120}
5121
Eric Laurente0720872014-03-11 09:30:41 -07005122void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005123 bool on,
5124 audio_io_handle_t output,
5125 int delayMs,
5126 audio_devices_t device)
5127{
5128 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005129 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
5130 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5131 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005132 }
5133 }
5134}
5135
Eric Laurente0720872014-03-11 09:30:41 -07005136void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005137 bool on,
5138 audio_io_handle_t output,
5139 int delayMs,
5140 audio_devices_t device)
5141{
5142 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005143 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005144 if (device == AUDIO_DEVICE_NONE) {
5145 device = outputDesc->device();
5146 }
5147
5148 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5149 stream, on, output, outputDesc->mMuteCount[stream], device);
5150
5151 if (on) {
5152 if (outputDesc->mMuteCount[stream] == 0) {
5153 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005154 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5155 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005156 checkAndSetVolume(stream, 0, output, device, delayMs);
5157 }
5158 }
5159 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5160 outputDesc->mMuteCount[stream]++;
5161 } else {
5162 if (outputDesc->mMuteCount[stream] == 0) {
5163 ALOGV("setStreamMute() unmuting non muted stream!");
5164 return;
5165 }
5166 if (--outputDesc->mMuteCount[stream] == 0) {
5167 checkAndSetVolume(stream,
5168 streamDesc.getVolumeIndex(device),
5169 output,
5170 device,
5171 delayMs);
5172 }
5173 }
5174}
5175
Eric Laurente0720872014-03-11 09:30:41 -07005176void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005177 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005178{
5179 // if the stream pertains to sonification strategy and we are in call we must
5180 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5181 // in the device used for phone strategy and play the tone if the selected device does not
5182 // interfere with the device used for phone strategy
5183 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5184 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005185 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005186 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5187 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005188 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005189 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5190 stream, starting, outputDesc->mDevice, stateChange);
5191 if (outputDesc->mRefCount[stream]) {
5192 int muteCount = 1;
5193 if (stateChange) {
5194 muteCount = outputDesc->mRefCount[stream];
5195 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005196 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005197 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5198 for (int i = 0; i < muteCount; i++) {
5199 setStreamMute(stream, starting, mPrimaryOutput);
5200 }
5201 } else {
5202 ALOGV("handleIncallSonification() high visibility");
5203 if (outputDesc->device() &
5204 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5205 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5206 for (int i = 0; i < muteCount; i++) {
5207 setStreamMute(stream, starting, mPrimaryOutput);
5208 }
5209 }
5210 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005211 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5212 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005213 } else {
5214 mpClientInterface->stopTone();
5215 }
5216 }
5217 }
5218 }
5219}
5220
Eric Laurente0720872014-03-11 09:30:41 -07005221bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005222{
5223 return isStateInCall(mPhoneState);
5224}
5225
Eric Laurente0720872014-03-11 09:30:41 -07005226bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005227 return ((state == AUDIO_MODE_IN_CALL) ||
5228 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005229}
5230
Eric Laurente0720872014-03-11 09:30:41 -07005231uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005232{
5233 return MAX_EFFECTS_CPU_LOAD;
5234}
5235
Eric Laurente0720872014-03-11 09:30:41 -07005236uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005237{
5238 return MAX_EFFECTS_MEMORY;
5239}
5240
Eric Laurent6a94d692014-05-20 11:18:06 -07005241
Eric Laurente552edb2014-03-10 17:42:56 -07005242// --- AudioOutputDescriptor class implementation
5243
Eric Laurente0720872014-03-11 09:30:41 -07005244AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005245 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005246 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005247 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005248 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5249{
5250 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005251 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005252 mRefCount[i] = 0;
5253 mCurVolume[i] = -1.0;
5254 mMuteCount[i] = 0;
5255 mStopTime[i] = 0;
5256 }
5257 for (int i = 0; i < NUM_STRATEGIES; i++) {
5258 mStrategyMutedByDevice[i] = false;
5259 }
5260 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005261 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005262 mSamplingRate = profile->pickSamplingRate();
5263 mFormat = profile->pickFormat();
5264 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005265 if (profile->mGains.size() > 0) {
5266 profile->mGains[0]->getDefaultConfig(&mGain);
5267 }
Eric Laurente552edb2014-03-10 17:42:56 -07005268 }
5269}
5270
Eric Laurente0720872014-03-11 09:30:41 -07005271audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005272{
5273 if (isDuplicated()) {
5274 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5275 } else {
5276 return mDevice;
5277 }
5278}
5279
Eric Laurente0720872014-03-11 09:30:41 -07005280uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005281{
5282 if (isDuplicated()) {
5283 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5284 } else {
5285 return mLatency;
5286 }
5287}
5288
Eric Laurente0720872014-03-11 09:30:41 -07005289bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005290 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005291{
5292 if (isDuplicated()) {
5293 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5294 } else if (outputDesc->isDuplicated()){
5295 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5296 } else {
5297 return (mProfile->mModule == outputDesc->mProfile->mModule);
5298 }
5299}
5300
Eric Laurente0720872014-03-11 09:30:41 -07005301void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005302 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005303{
5304 // forward usage count change to attached outputs
5305 if (isDuplicated()) {
5306 mOutput1->changeRefCount(stream, delta);
5307 mOutput2->changeRefCount(stream, delta);
5308 }
5309 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005310 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5311 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005312 mRefCount[stream] = 0;
5313 return;
5314 }
5315 mRefCount[stream] += delta;
5316 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5317}
5318
Eric Laurente0720872014-03-11 09:30:41 -07005319audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005320{
5321 if (isDuplicated()) {
5322 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5323 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005324 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005325 }
5326}
5327
Eric Laurente0720872014-03-11 09:30:41 -07005328bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07005329{
5330 return isStrategyActive(NUM_STRATEGIES, inPastMs);
5331}
5332
Eric Laurente0720872014-03-11 09:30:41 -07005333bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005334 uint32_t inPastMs,
5335 nsecs_t sysTime) const
5336{
5337 if ((sysTime == 0) && (inPastMs != 0)) {
5338 sysTime = systemTime();
5339 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005340 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5341 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005342 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005343 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005344 return true;
5345 }
5346 }
5347 return false;
5348}
5349
Eric Laurente0720872014-03-11 09:30:41 -07005350bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005351 uint32_t inPastMs,
5352 nsecs_t sysTime) const
5353{
5354 if (mRefCount[stream] != 0) {
5355 return true;
5356 }
5357 if (inPastMs == 0) {
5358 return false;
5359 }
5360 if (sysTime == 0) {
5361 sysTime = systemTime();
5362 }
5363 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
5364 return true;
5365 }
5366 return false;
5367}
5368
Eric Laurent1c333e22014-05-20 10:48:17 -07005369void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005370 struct audio_port_config *dstConfig,
5371 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005372{
Eric Laurent84c70242014-06-23 08:46:27 -07005373 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
5374
Eric Laurent1f2f2232014-06-02 12:01:23 -07005375 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5376 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5377 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005378 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005379 }
5380 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5381
Eric Laurent6a94d692014-05-20 11:18:06 -07005382 dstConfig->id = mId;
5383 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
5384 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07005385 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5386 dstConfig->ext.mix.handle = mIoHandle;
5387 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07005388}
5389
5390void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
5391 struct audio_port *port) const
5392{
Eric Laurent84c70242014-06-23 08:46:27 -07005393 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005394 mProfile->toAudioPort(port);
5395 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005396 toAudioPortConfig(&port->active_config);
5397 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005398 port->ext.mix.handle = mIoHandle;
5399 port->ext.mix.latency_class =
5400 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
5401}
Eric Laurente552edb2014-03-10 17:42:56 -07005402
Eric Laurente0720872014-03-11 09:30:41 -07005403status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005404{
5405 const size_t SIZE = 256;
5406 char buffer[SIZE];
5407 String8 result;
5408
Eric Laurent4d416952014-08-10 14:07:09 -07005409 snprintf(buffer, SIZE, " ID: %d\n", mId);
5410 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005411 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5412 result.append(buffer);
5413 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
5414 result.append(buffer);
5415 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5416 result.append(buffer);
5417 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
5418 result.append(buffer);
5419 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
5420 result.append(buffer);
5421 snprintf(buffer, SIZE, " Devices %08x\n", device());
5422 result.append(buffer);
5423 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
5424 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07005425 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5426 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
5427 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07005428 result.append(buffer);
5429 }
5430 write(fd, result.string(), result.size());
5431
5432 return NO_ERROR;
5433}
5434
5435// --- AudioInputDescriptor class implementation
5436
Eric Laurent1c333e22014-05-20 10:48:17 -07005437AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005438 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07005439 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005440 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07005441{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005442 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005443 mSamplingRate = profile->pickSamplingRate();
5444 mFormat = profile->pickFormat();
5445 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005446 if (profile->mGains.size() > 0) {
5447 profile->mGains[0]->getDefaultConfig(&mGain);
5448 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005449 }
Eric Laurente552edb2014-03-10 17:42:56 -07005450}
5451
Eric Laurent1c333e22014-05-20 10:48:17 -07005452void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07005453 struct audio_port_config *dstConfig,
5454 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005455{
Eric Laurent84c70242014-06-23 08:46:27 -07005456 ALOG_ASSERT(mProfile != 0,
5457 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07005458 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
5459 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
5460 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07005461 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005462 }
5463
5464 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5465
Eric Laurent6a94d692014-05-20 11:18:06 -07005466 dstConfig->id = mId;
5467 dstConfig->role = AUDIO_PORT_ROLE_SINK;
5468 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07005469 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
5470 dstConfig->ext.mix.handle = mIoHandle;
5471 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07005472}
5473
5474void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5475 struct audio_port *port) const
5476{
Eric Laurent84c70242014-06-23 08:46:27 -07005477 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5478
Eric Laurent1c333e22014-05-20 10:48:17 -07005479 mProfile->toAudioPort(port);
5480 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005481 toAudioPortConfig(&port->active_config);
5482 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005483 port->ext.mix.handle = mIoHandle;
5484 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5485}
5486
Eric Laurente0720872014-03-11 09:30:41 -07005487status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005488{
5489 const size_t SIZE = 256;
5490 char buffer[SIZE];
5491 String8 result;
5492
Eric Laurent4d416952014-08-10 14:07:09 -07005493 snprintf(buffer, SIZE, " ID: %d\n", mId);
5494 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005495 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5496 result.append(buffer);
5497 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5498 result.append(buffer);
5499 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5500 result.append(buffer);
5501 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5502 result.append(buffer);
5503 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5504 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005505 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5506 result.append(buffer);
5507
Eric Laurente552edb2014-03-10 17:42:56 -07005508 write(fd, result.string(), result.size());
5509
5510 return NO_ERROR;
5511}
5512
5513// --- StreamDescriptor class implementation
5514
Eric Laurente0720872014-03-11 09:30:41 -07005515AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07005516 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5517{
5518 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5519}
5520
Eric Laurente0720872014-03-11 09:30:41 -07005521int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005522{
Eric Laurente0720872014-03-11 09:30:41 -07005523 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005524 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5525 if (mIndexCur.indexOfKey(device) < 0) {
5526 device = AUDIO_DEVICE_OUT_DEFAULT;
5527 }
5528 return mIndexCur.valueFor(device);
5529}
5530
Eric Laurente0720872014-03-11 09:30:41 -07005531void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005532{
5533 const size_t SIZE = 256;
5534 char buffer[SIZE];
5535 String8 result;
5536
5537 snprintf(buffer, SIZE, "%s %02d %02d ",
5538 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5539 result.append(buffer);
5540 for (size_t i = 0; i < mIndexCur.size(); i++) {
5541 snprintf(buffer, SIZE, "%04x : %02d, ",
5542 mIndexCur.keyAt(i),
5543 mIndexCur.valueAt(i));
5544 result.append(buffer);
5545 }
5546 result.append("\n");
5547
5548 write(fd, result.string(), result.size());
5549}
5550
5551// --- EffectDescriptor class implementation
5552
Eric Laurente0720872014-03-11 09:30:41 -07005553status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005554{
5555 const size_t SIZE = 256;
5556 char buffer[SIZE];
5557 String8 result;
5558
5559 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5560 result.append(buffer);
5561 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5562 result.append(buffer);
5563 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5564 result.append(buffer);
5565 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5566 result.append(buffer);
5567 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5568 result.append(buffer);
5569 write(fd, result.string(), result.size());
5570
5571 return NO_ERROR;
5572}
5573
Eric Laurent1c333e22014-05-20 10:48:17 -07005574// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005575
Eric Laurente0720872014-03-11 09:30:41 -07005576AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005577 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5578 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005579{
5580}
5581
Eric Laurente0720872014-03-11 09:30:41 -07005582AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005583{
5584 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005585 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005586 }
5587 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005588 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005589 }
5590 free((void *)mName);
5591}
5592
Eric Laurent1afeecb2014-05-14 08:52:28 -07005593status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5594{
5595 cnode *node = root->first_child;
5596
5597 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5598
5599 while (node) {
5600 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5601 profile->loadSamplingRates((char *)node->value);
5602 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5603 profile->loadFormats((char *)node->value);
5604 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5605 profile->loadInChannels((char *)node->value);
5606 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5607 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5608 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07005609 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5610 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005611 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5612 profile->loadGains(node);
5613 }
5614 node = node->next;
5615 }
5616 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5617 "loadInput() invalid supported devices");
5618 ALOGW_IF(profile->mChannelMasks.size() == 0,
5619 "loadInput() invalid supported channel masks");
5620 ALOGW_IF(profile->mSamplingRates.size() == 0,
5621 "loadInput() invalid supported sampling rates");
5622 ALOGW_IF(profile->mFormats.size() == 0,
5623 "loadInput() invalid supported formats");
5624 if (!profile->mSupportedDevices.isEmpty() &&
5625 (profile->mChannelMasks.size() != 0) &&
5626 (profile->mSamplingRates.size() != 0) &&
5627 (profile->mFormats.size() != 0)) {
5628
5629 ALOGV("loadInput() adding input Supported Devices %04x",
5630 profile->mSupportedDevices.types());
5631
5632 mInputProfiles.add(profile);
5633 return NO_ERROR;
5634 } else {
5635 return BAD_VALUE;
5636 }
5637}
5638
5639status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5640{
5641 cnode *node = root->first_child;
5642
5643 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5644
5645 while (node) {
5646 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5647 profile->loadSamplingRates((char *)node->value);
5648 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5649 profile->loadFormats((char *)node->value);
5650 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5651 profile->loadOutChannels((char *)node->value);
5652 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5653 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5654 mDeclaredDevices);
5655 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005656 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005657 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5658 profile->loadGains(node);
5659 }
5660 node = node->next;
5661 }
5662 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5663 "loadOutput() invalid supported devices");
5664 ALOGW_IF(profile->mChannelMasks.size() == 0,
5665 "loadOutput() invalid supported channel masks");
5666 ALOGW_IF(profile->mSamplingRates.size() == 0,
5667 "loadOutput() invalid supported sampling rates");
5668 ALOGW_IF(profile->mFormats.size() == 0,
5669 "loadOutput() invalid supported formats");
5670 if (!profile->mSupportedDevices.isEmpty() &&
5671 (profile->mChannelMasks.size() != 0) &&
5672 (profile->mSamplingRates.size() != 0) &&
5673 (profile->mFormats.size() != 0)) {
5674
5675 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5676 profile->mSupportedDevices.types(), profile->mFlags);
5677
5678 mOutputProfiles.add(profile);
5679 return NO_ERROR;
5680 } else {
5681 return BAD_VALUE;
5682 }
5683}
5684
5685status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5686{
5687 cnode *node = root->first_child;
5688
5689 audio_devices_t type = AUDIO_DEVICE_NONE;
5690 while (node) {
5691 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5692 type = parseDeviceNames((char *)node->value);
5693 break;
5694 }
5695 node = node->next;
5696 }
5697 if (type == AUDIO_DEVICE_NONE ||
5698 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5699 ALOGW("loadDevice() bad type %08x", type);
5700 return BAD_VALUE;
5701 }
5702 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5703 deviceDesc->mModule = this;
5704
5705 node = root->first_child;
5706 while (node) {
5707 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5708 deviceDesc->mAddress = String8((char *)node->value);
5709 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5710 if (audio_is_input_device(type)) {
5711 deviceDesc->loadInChannels((char *)node->value);
5712 } else {
5713 deviceDesc->loadOutChannels((char *)node->value);
5714 }
5715 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5716 deviceDesc->loadGains(node);
5717 }
5718 node = node->next;
5719 }
5720
5721 ALOGV("loadDevice() adding device name %s type %08x address %s",
5722 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5723
5724 mDeclaredDevices.add(deviceDesc);
5725
5726 return NO_ERROR;
5727}
5728
Eric Laurente0720872014-03-11 09:30:41 -07005729void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005730{
5731 const size_t SIZE = 256;
5732 char buffer[SIZE];
5733 String8 result;
5734
5735 snprintf(buffer, SIZE, " - name: %s\n", mName);
5736 result.append(buffer);
5737 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5738 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005739 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5740 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005741 write(fd, result.string(), result.size());
5742 if (mOutputProfiles.size()) {
5743 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5744 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005745 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005746 write(fd, buffer, strlen(buffer));
5747 mOutputProfiles[i]->dump(fd);
5748 }
5749 }
5750 if (mInputProfiles.size()) {
5751 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5752 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005753 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005754 write(fd, buffer, strlen(buffer));
5755 mInputProfiles[i]->dump(fd);
5756 }
5757 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005758 if (mDeclaredDevices.size()) {
5759 write(fd, " - devices:\n", strlen(" - devices:\n"));
5760 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5761 mDeclaredDevices[i]->dump(fd, 4, i);
5762 }
5763 }
Eric Laurente552edb2014-03-10 17:42:56 -07005764}
5765
Eric Laurent1c333e22014-05-20 10:48:17 -07005766// --- AudioPort class implementation
5767
Eric Laurenta121f902014-06-03 13:32:54 -07005768
5769AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5770 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07005771 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07005772{
5773 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5774 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5775}
5776
Eric Laurent1c333e22014-05-20 10:48:17 -07005777void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5778{
5779 port->role = mRole;
5780 port->type = mType;
5781 unsigned int i;
5782 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005783 if (mSamplingRates[i] != 0) {
5784 port->sample_rates[i] = mSamplingRates[i];
5785 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005786 }
5787 port->num_sample_rates = i;
5788 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005789 if (mChannelMasks[i] != 0) {
5790 port->channel_masks[i] = mChannelMasks[i];
5791 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005792 }
5793 port->num_channel_masks = i;
5794 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005795 if (mFormats[i] != 0) {
5796 port->formats[i] = mFormats[i];
5797 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005798 }
5799 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005800
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005801 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005802
5803 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5804 port->gains[i] = mGains[i]->mGain;
5805 }
5806 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005807}
5808
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005809void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
5810 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
5811 const uint32_t rate = port->mSamplingRates.itemAt(k);
5812 if (rate != 0) { // skip "dynamic" rates
5813 bool hasRate = false;
5814 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
5815 if (rate == mSamplingRates.itemAt(l)) {
5816 hasRate = true;
5817 break;
5818 }
5819 }
5820 if (!hasRate) { // never import a sampling rate twice
5821 mSamplingRates.add(rate);
5822 }
5823 }
5824 }
5825 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
5826 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
5827 if (mask != 0) { // skip "dynamic" masks
5828 bool hasMask = false;
5829 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
5830 if (mask == mChannelMasks.itemAt(l)) {
5831 hasMask = true;
5832 break;
5833 }
5834 }
5835 if (!hasMask) { // never import a channel mask twice
5836 mChannelMasks.add(mask);
5837 }
5838 }
5839 }
5840 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
5841 const audio_format_t format = port->mFormats.itemAt(k);
5842 if (format != 0) { // skip "dynamic" formats
5843 bool hasFormat = false;
5844 for (size_t l = 0 ; l < mFormats.size() ; l++) {
5845 if (format == mFormats.itemAt(l)) {
5846 hasFormat = true;
5847 break;
5848 }
5849 }
5850 if (!hasFormat) { // never import a channel mask twice
5851 mFormats.add(format);
5852 }
5853 }
5854 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08005855 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
5856 sp<AudioGain> gain = port->mGains.itemAt(k);
5857 if (gain != 0) {
5858 bool hasGain = false;
5859 for (size_t l = 0 ; l < mGains.size() ; l++) {
5860 if (gain == mGains.itemAt(l)) {
5861 hasGain = true;
5862 break;
5863 }
5864 }
5865 if (!hasGain) { // never import a gain twice
5866 mGains.add(gain);
5867 }
5868 }
5869 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005870}
5871
5872void AudioPolicyManager::AudioPort::clearCapabilities() {
5873 mChannelMasks.clear();
5874 mFormats.clear();
5875 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08005876 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005877}
Eric Laurent1c333e22014-05-20 10:48:17 -07005878
5879void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5880{
5881 char *str = strtok(name, "|");
5882
5883 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5884 // rates should be read from the output stream after it is opened for the first time
5885 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5886 mSamplingRates.add(0);
5887 return;
5888 }
5889
5890 while (str != NULL) {
5891 uint32_t rate = atoi(str);
5892 if (rate != 0) {
5893 ALOGV("loadSamplingRates() adding rate %d", rate);
5894 mSamplingRates.add(rate);
5895 }
5896 str = strtok(NULL, "|");
5897 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005898}
5899
5900void AudioPolicyManager::AudioPort::loadFormats(char *name)
5901{
5902 char *str = strtok(name, "|");
5903
5904 // by convention, "0' in the first entry in mFormats indicates the supported formats
5905 // should be read from the output stream after it is opened for the first time
5906 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5907 mFormats.add(AUDIO_FORMAT_DEFAULT);
5908 return;
5909 }
5910
5911 while (str != NULL) {
5912 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5913 ARRAY_SIZE(sFormatNameToEnumTable),
5914 str);
5915 if (format != AUDIO_FORMAT_DEFAULT) {
5916 mFormats.add(format);
5917 }
5918 str = strtok(NULL, "|");
5919 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005920}
5921
5922void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5923{
5924 const char *str = strtok(name, "|");
5925
5926 ALOGV("loadInChannels() %s", name);
5927
5928 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5929 mChannelMasks.add(0);
5930 return;
5931 }
5932
5933 while (str != NULL) {
5934 audio_channel_mask_t channelMask =
5935 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5936 ARRAY_SIZE(sInChannelsNameToEnumTable),
5937 str);
5938 if (channelMask != 0) {
5939 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5940 mChannelMasks.add(channelMask);
5941 }
5942 str = strtok(NULL, "|");
5943 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005944}
5945
5946void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5947{
5948 const char *str = strtok(name, "|");
5949
5950 ALOGV("loadOutChannels() %s", name);
5951
5952 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5953 // masks should be read from the output stream after it is opened for the first time
5954 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5955 mChannelMasks.add(0);
5956 return;
5957 }
5958
5959 while (str != NULL) {
5960 audio_channel_mask_t channelMask =
5961 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5962 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5963 str);
5964 if (channelMask != 0) {
5965 mChannelMasks.add(channelMask);
5966 }
5967 str = strtok(NULL, "|");
5968 }
5969 return;
5970}
5971
Eric Laurent1afeecb2014-05-14 08:52:28 -07005972audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5973{
5974 const char *str = strtok(name, "|");
5975
5976 ALOGV("loadGainMode() %s", name);
5977 audio_gain_mode_t mode = 0;
5978 while (str != NULL) {
5979 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5980 ARRAY_SIZE(sGainModeNameToEnumTable),
5981 str);
5982 str = strtok(NULL, "|");
5983 }
5984 return mode;
5985}
5986
Eric Laurenta121f902014-06-03 13:32:54 -07005987void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005988{
5989 cnode *node = root->first_child;
5990
Eric Laurenta121f902014-06-03 13:32:54 -07005991 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005992
5993 while (node) {
5994 if (strcmp(node->name, GAIN_MODE) == 0) {
5995 gain->mGain.mode = loadGainMode((char *)node->value);
5996 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005997 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005998 gain->mGain.channel_mask =
5999 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6000 ARRAY_SIZE(sInChannelsNameToEnumTable),
6001 (char *)node->value);
6002 } else {
6003 gain->mGain.channel_mask =
6004 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6005 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6006 (char *)node->value);
6007 }
6008 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6009 gain->mGain.min_value = atoi((char *)node->value);
6010 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6011 gain->mGain.max_value = atoi((char *)node->value);
6012 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6013 gain->mGain.default_value = atoi((char *)node->value);
6014 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6015 gain->mGain.step_value = atoi((char *)node->value);
6016 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6017 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6018 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6019 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6020 }
6021 node = node->next;
6022 }
6023
6024 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6025 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6026
6027 if (gain->mGain.mode == 0) {
6028 return;
6029 }
6030 mGains.add(gain);
6031}
6032
6033void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6034{
6035 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006036 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006037 while (node) {
6038 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006039 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006040 node = node->next;
6041 }
6042}
6043
Glenn Kastencbd48022014-07-24 13:46:44 -07006044status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006045{
6046 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6047 if (mSamplingRates[i] == samplingRate) {
6048 return NO_ERROR;
6049 }
6050 }
6051 return BAD_VALUE;
6052}
6053
Glenn Kastencbd48022014-07-24 13:46:44 -07006054status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6055 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006056{
Glenn Kastencbd48022014-07-24 13:46:44 -07006057 // Search for the closest supported sampling rate that is above (preferred)
6058 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6059 // The sampling rates do not need to be sorted in ascending order.
6060 ssize_t maxBelow = -1;
6061 ssize_t minAbove = -1;
6062 uint32_t candidate;
6063 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6064 candidate = mSamplingRates[i];
6065 if (candidate == samplingRate) {
6066 if (updatedSamplingRate != NULL) {
6067 *updatedSamplingRate = candidate;
6068 }
6069 return NO_ERROR;
6070 }
6071 // candidate < desired
6072 if (candidate < samplingRate) {
6073 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6074 maxBelow = i;
6075 }
6076 // candidate > desired
6077 } else {
6078 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6079 minAbove = i;
6080 }
6081 }
6082 }
6083 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6084 // TODO Move these assumptions out.
6085 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6086 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6087 // due to approximation by an int32_t of the
6088 // phase increments
6089 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6090 if (minAbove >= 0) {
6091 candidate = mSamplingRates[minAbove];
6092 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6093 if (updatedSamplingRate != NULL) {
6094 *updatedSamplingRate = candidate;
6095 }
6096 return NO_ERROR;
6097 }
6098 }
6099 // But if we have to up-sample from a lower sampling rate, that's OK.
6100 if (maxBelow >= 0) {
6101 candidate = mSamplingRates[maxBelow];
6102 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6103 if (updatedSamplingRate != NULL) {
6104 *updatedSamplingRate = candidate;
6105 }
6106 return NO_ERROR;
6107 }
6108 }
6109 // leave updatedSamplingRate unmodified
6110 return BAD_VALUE;
6111}
6112
6113status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6114{
6115 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006116 if (mChannelMasks[i] == channelMask) {
6117 return NO_ERROR;
6118 }
6119 }
6120 return BAD_VALUE;
6121}
6122
Glenn Kastencbd48022014-07-24 13:46:44 -07006123status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6124 const
6125{
6126 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6127 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6128 // FIXME Does not handle multi-channel automatic conversions yet
6129 audio_channel_mask_t supported = mChannelMasks[i];
6130 if (supported == channelMask) {
6131 return NO_ERROR;
6132 }
6133 if (isRecordThread) {
6134 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6135 // FIXME Abstract this out to a table.
6136 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6137 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6138 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6139 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6140 return NO_ERROR;
6141 }
6142 }
6143 }
6144 return BAD_VALUE;
6145}
6146
Eric Laurenta121f902014-06-03 13:32:54 -07006147status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6148{
6149 for (size_t i = 0; i < mFormats.size(); i ++) {
6150 if (mFormats[i] == format) {
6151 return NO_ERROR;
6152 }
6153 }
6154 return BAD_VALUE;
6155}
6156
Eric Laurent1e693b52014-07-09 15:03:28 -07006157
6158uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6159{
6160 // special case for uninitialized dynamic profile
6161 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6162 return 0;
6163 }
6164
Eric Laurent828bcff2014-09-07 12:26:06 -07006165 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6166 // channel count / sampling rate combination chosen will be supported by the connected
6167 // sink
6168 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6169 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6170 uint32_t samplingRate = UINT_MAX;
6171 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6172 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6173 samplingRate = mSamplingRates[i];
6174 }
6175 }
6176 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6177 }
6178
Eric Laurent1e693b52014-07-09 15:03:28 -07006179 uint32_t samplingRate = 0;
6180 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6181
6182 // For mixed output and inputs, use max mixer sampling rates. Do not
6183 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006184 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006185 maxRate = UINT_MAX;
6186 }
6187 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6188 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6189 samplingRate = mSamplingRates[i];
6190 }
6191 }
6192 return samplingRate;
6193}
6194
6195audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6196{
6197 // special case for uninitialized dynamic profile
6198 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6199 return AUDIO_CHANNEL_NONE;
6200 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006201 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006202
6203 // For direct outputs, pick minimum channel count: this helps ensuring that the
6204 // channel count / sampling rate combination chosen will be supported by the connected
6205 // sink
6206 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6207 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6208 uint32_t channelCount = UINT_MAX;
6209 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6210 uint32_t cnlCount;
6211 if (mUseInChannelMask) {
6212 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6213 } else {
6214 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6215 }
6216 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6217 channelMask = mChannelMasks[i];
6218 channelCount = cnlCount;
6219 }
6220 }
6221 return channelMask;
6222 }
6223
Eric Laurent1e693b52014-07-09 15:03:28 -07006224 uint32_t channelCount = 0;
6225 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6226
6227 // For mixed output and inputs, use max mixer channel count. Do not
6228 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006229 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006230 maxCount = UINT_MAX;
6231 }
6232 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6233 uint32_t cnlCount;
6234 if (mUseInChannelMask) {
6235 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6236 } else {
6237 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6238 }
6239 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6240 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006241 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006242 }
6243 }
6244 return channelMask;
6245}
6246
Andy Hung9a605382014-07-28 16:16:31 -07006247/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07006248const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
6249 AUDIO_FORMAT_DEFAULT,
6250 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07006251 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006252 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07006253 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07006254 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07006255};
6256
6257int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
6258 audio_format_t format2)
6259{
6260 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
6261 // compressed format and better than any PCM format. This is by design of pickFormat()
6262 if (!audio_is_linear_pcm(format1)) {
6263 if (!audio_is_linear_pcm(format2)) {
6264 return 0;
6265 }
6266 return 1;
6267 }
6268 if (!audio_is_linear_pcm(format2)) {
6269 return -1;
6270 }
6271
6272 int index1 = -1, index2 = -1;
6273 for (size_t i = 0;
6274 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
6275 i ++) {
6276 if (sPcmFormatCompareTable[i] == format1) {
6277 index1 = i;
6278 }
6279 if (sPcmFormatCompareTable[i] == format2) {
6280 index2 = i;
6281 }
6282 }
6283 // format1 not found => index1 < 0 => format2 > format1
6284 // format2 not found => index2 < 0 => format2 < format1
6285 return index1 - index2;
6286}
6287
6288audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
6289{
6290 // special case for uninitialized dynamic profile
6291 if (mFormats.size() == 1 && mFormats[0] == 0) {
6292 return AUDIO_FORMAT_DEFAULT;
6293 }
6294
6295 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07006296 audio_format_t bestFormat =
6297 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
6298 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07006299 // For mixed output and inputs, use best mixer output format. Do not
6300 // limit format otherwise
6301 if ((mType != AUDIO_PORT_TYPE_MIX) ||
6302 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07006303 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006304 bestFormat = AUDIO_FORMAT_INVALID;
6305 }
6306
6307 for (size_t i = 0; i < mFormats.size(); i ++) {
6308 if ((compareFormats(mFormats[i], format) > 0) &&
6309 (compareFormats(mFormats[i], bestFormat) <= 0)) {
6310 format = mFormats[i];
6311 }
6312 }
6313 return format;
6314}
6315
Eric Laurenta121f902014-06-03 13:32:54 -07006316status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
6317 int index) const
6318{
6319 if (index < 0 || (size_t)index >= mGains.size()) {
6320 return BAD_VALUE;
6321 }
6322 return mGains[index]->checkConfig(gainConfig);
6323}
6324
Eric Laurent1afeecb2014-05-14 08:52:28 -07006325void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
6326{
6327 const size_t SIZE = 256;
6328 char buffer[SIZE];
6329 String8 result;
6330
6331 if (mName.size() != 0) {
6332 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
6333 result.append(buffer);
6334 }
6335
6336 if (mSamplingRates.size() != 0) {
6337 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
6338 result.append(buffer);
6339 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006340 if (i == 0 && mSamplingRates[i] == 0) {
6341 snprintf(buffer, SIZE, "Dynamic");
6342 } else {
6343 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
6344 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006345 result.append(buffer);
6346 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
6347 }
6348 result.append("\n");
6349 }
6350
6351 if (mChannelMasks.size() != 0) {
6352 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
6353 result.append(buffer);
6354 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006355 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
6356
6357 if (i == 0 && mChannelMasks[i] == 0) {
6358 snprintf(buffer, SIZE, "Dynamic");
6359 } else {
6360 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
6361 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006362 result.append(buffer);
6363 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
6364 }
6365 result.append("\n");
6366 }
6367
6368 if (mFormats.size() != 0) {
6369 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
6370 result.append(buffer);
6371 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006372 const char *formatStr = enumToString(sFormatNameToEnumTable,
6373 ARRAY_SIZE(sFormatNameToEnumTable),
6374 mFormats[i]);
6375 if (i == 0 && strcmp(formatStr, "") == 0) {
6376 snprintf(buffer, SIZE, "Dynamic");
6377 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07006378 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07006379 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006380 result.append(buffer);
6381 result.append(i == (mFormats.size() - 1) ? "" : ", ");
6382 }
6383 result.append("\n");
6384 }
6385 write(fd, result.string(), result.size());
6386 if (mGains.size() != 0) {
6387 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
6388 write(fd, buffer, strlen(buffer) + 1);
6389 result.append(buffer);
6390 for (size_t i = 0; i < mGains.size(); i++) {
6391 mGains[i]->dump(fd, spaces + 2, i);
6392 }
6393 }
6394}
6395
6396// --- AudioGain class implementation
6397
Eric Laurenta121f902014-06-03 13:32:54 -07006398AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006399{
Eric Laurenta121f902014-06-03 13:32:54 -07006400 mIndex = index;
6401 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006402 memset(&mGain, 0, sizeof(struct audio_gain));
6403}
6404
Eric Laurenta121f902014-06-03 13:32:54 -07006405void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
6406{
6407 config->index = mIndex;
6408 config->mode = mGain.mode;
6409 config->channel_mask = mGain.channel_mask;
6410 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6411 config->values[0] = mGain.default_value;
6412 } else {
6413 uint32_t numValues;
6414 if (mUseInChannelMask) {
6415 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
6416 } else {
6417 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
6418 }
6419 for (size_t i = 0; i < numValues; i++) {
6420 config->values[i] = mGain.default_value;
6421 }
6422 }
6423 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6424 config->ramp_duration_ms = mGain.min_ramp_ms;
6425 }
6426}
6427
6428status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
6429{
6430 if ((config->mode & ~mGain.mode) != 0) {
6431 return BAD_VALUE;
6432 }
6433 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
6434 if ((config->values[0] < mGain.min_value) ||
6435 (config->values[0] > mGain.max_value)) {
6436 return BAD_VALUE;
6437 }
6438 } else {
6439 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
6440 return BAD_VALUE;
6441 }
6442 uint32_t numValues;
6443 if (mUseInChannelMask) {
6444 numValues = audio_channel_count_from_in_mask(config->channel_mask);
6445 } else {
6446 numValues = audio_channel_count_from_out_mask(config->channel_mask);
6447 }
6448 for (size_t i = 0; i < numValues; i++) {
6449 if ((config->values[i] < mGain.min_value) ||
6450 (config->values[i] > mGain.max_value)) {
6451 return BAD_VALUE;
6452 }
6453 }
6454 }
6455 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
6456 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
6457 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
6458 return BAD_VALUE;
6459 }
6460 }
6461 return NO_ERROR;
6462}
6463
Eric Laurent1afeecb2014-05-14 08:52:28 -07006464void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
6465{
6466 const size_t SIZE = 256;
6467 char buffer[SIZE];
6468 String8 result;
6469
6470 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
6471 result.append(buffer);
6472 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
6473 result.append(buffer);
6474 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
6475 result.append(buffer);
6476 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
6477 result.append(buffer);
6478 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
6479 result.append(buffer);
6480 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
6481 result.append(buffer);
6482 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
6483 result.append(buffer);
6484 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
6485 result.append(buffer);
6486 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
6487 result.append(buffer);
6488
6489 write(fd, result.string(), result.size());
6490}
6491
Eric Laurent1f2f2232014-06-02 12:01:23 -07006492// --- AudioPortConfig class implementation
6493
6494AudioPolicyManager::AudioPortConfig::AudioPortConfig()
6495{
6496 mSamplingRate = 0;
6497 mChannelMask = AUDIO_CHANNEL_NONE;
6498 mFormat = AUDIO_FORMAT_INVALID;
6499 mGain.index = -1;
6500}
6501
Eric Laurenta121f902014-06-03 13:32:54 -07006502status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
6503 const struct audio_port_config *config,
6504 struct audio_port_config *backupConfig)
6505{
6506 struct audio_port_config localBackupConfig;
6507 status_t status = NO_ERROR;
6508
6509 localBackupConfig.config_mask = config->config_mask;
6510 toAudioPortConfig(&localBackupConfig);
6511
Marco Nelissen961ec212014-08-25 15:58:39 -07006512 sp<AudioPort> audioport = getAudioPort();
6513 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006514 status = NO_INIT;
6515 goto exit;
6516 }
6517 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006518 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07006519 if (status != NO_ERROR) {
6520 goto exit;
6521 }
6522 mSamplingRate = config->sample_rate;
6523 }
6524 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006525 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07006526 if (status != NO_ERROR) {
6527 goto exit;
6528 }
6529 mChannelMask = config->channel_mask;
6530 }
6531 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006532 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07006533 if (status != NO_ERROR) {
6534 goto exit;
6535 }
6536 mFormat = config->format;
6537 }
6538 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07006539 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07006540 if (status != NO_ERROR) {
6541 goto exit;
6542 }
6543 mGain = config->gain;
6544 }
6545
6546exit:
6547 if (status != NO_ERROR) {
6548 applyAudioPortConfig(&localBackupConfig);
6549 }
6550 if (backupConfig != NULL) {
6551 *backupConfig = localBackupConfig;
6552 }
6553 return status;
6554}
6555
Eric Laurent1f2f2232014-06-02 12:01:23 -07006556void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
6557 struct audio_port_config *dstConfig,
6558 const struct audio_port_config *srcConfig) const
6559{
6560 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
6561 dstConfig->sample_rate = mSamplingRate;
6562 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
6563 dstConfig->sample_rate = srcConfig->sample_rate;
6564 }
6565 } else {
6566 dstConfig->sample_rate = 0;
6567 }
6568 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
6569 dstConfig->channel_mask = mChannelMask;
6570 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
6571 dstConfig->channel_mask = srcConfig->channel_mask;
6572 }
6573 } else {
6574 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
6575 }
6576 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
6577 dstConfig->format = mFormat;
6578 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
6579 dstConfig->format = srcConfig->format;
6580 }
6581 } else {
6582 dstConfig->format = AUDIO_FORMAT_INVALID;
6583 }
6584 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6585 dstConfig->gain = mGain;
6586 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6587 dstConfig->gain = srcConfig->gain;
6588 }
6589 } else {
6590 dstConfig->gain.index = -1;
6591 }
6592 if (dstConfig->gain.index != -1) {
6593 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6594 } else {
6595 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6596 }
6597}
6598
Eric Laurent1c333e22014-05-20 10:48:17 -07006599// --- IOProfile class implementation
6600
Eric Laurent1afeecb2014-05-14 08:52:28 -07006601AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07006602 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07006603 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07006604{
6605}
6606
Eric Laurente0720872014-03-11 09:30:41 -07006607AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07006608{
6609}
6610
6611// checks if the IO profile is compatible with specified parameters.
6612// Sampling rate, format and channel mask must be specified in order to
6613// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07006614bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07006615 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07006616 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07006617 audio_format_t format,
6618 audio_channel_mask_t channelMask,
Eric Laurent5dbe4712014-09-19 19:04:57 -07006619 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07006620{
Glenn Kastencbd48022014-07-24 13:46:44 -07006621 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6622 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6623 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07006624
Glenn Kastencbd48022014-07-24 13:46:44 -07006625 if ((mSupportedDevices.types() & device) != device) {
6626 return false;
6627 }
6628
6629 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07006630 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006631 }
6632 uint32_t myUpdatedSamplingRate = samplingRate;
6633 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006634 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006635 }
6636 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6637 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07006638 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07006639 }
6640
6641 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6642 return false;
6643 }
6644
6645 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6646 checkExactChannelMask(channelMask) != NO_ERROR)) {
6647 return false;
6648 }
6649 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6650 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6651 return false;
6652 }
6653
6654 if (isPlaybackThread && (mFlags & flags) != flags) {
6655 return false;
6656 }
6657 // The only input flag that is allowed to be different is the fast flag.
6658 // An existing fast stream is compatible with a normal track request.
6659 // An existing normal stream is compatible with a fast track request,
6660 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07006661 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07006662 ~AUDIO_INPUT_FLAG_FAST)) {
6663 return false;
6664 }
6665
6666 if (updatedSamplingRate != NULL) {
6667 *updatedSamplingRate = myUpdatedSamplingRate;
6668 }
6669 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006670}
6671
Eric Laurente0720872014-03-11 09:30:41 -07006672void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006673{
6674 const size_t SIZE = 256;
6675 char buffer[SIZE];
6676 String8 result;
6677
Eric Laurent1afeecb2014-05-14 08:52:28 -07006678 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006679
Eric Laurente552edb2014-03-10 17:42:56 -07006680 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6681 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006682 snprintf(buffer, SIZE, " - devices:\n");
6683 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006684 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006685 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6686 mSupportedDevices[i]->dump(fd, 6, i);
6687 }
Eric Laurente552edb2014-03-10 17:42:56 -07006688}
6689
Eric Laurentd4692962014-05-05 18:13:44 -07006690void AudioPolicyManager::IOProfile::log()
6691{
6692 const size_t SIZE = 256;
6693 char buffer[SIZE];
6694 String8 result;
6695
6696 ALOGV(" - sampling rates: ");
6697 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6698 ALOGV(" %d", mSamplingRates[i]);
6699 }
6700
6701 ALOGV(" - channel masks: ");
6702 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6703 ALOGV(" 0x%04x", mChannelMasks[i]);
6704 }
6705
6706 ALOGV(" - formats: ");
6707 for (size_t i = 0; i < mFormats.size(); i++) {
6708 ALOGV(" 0x%08x", mFormats[i]);
6709 }
6710
6711 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6712 ALOGV(" - flags: 0x%04x\n", mFlags);
6713}
6714
6715
Eric Laurent3a4311c2014-03-17 12:00:47 -07006716// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006717
Eric Laurent1f2f2232014-06-02 12:01:23 -07006718
6719AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6720 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6721 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6722 AUDIO_PORT_ROLE_SOURCE,
6723 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006724 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006725{
Eric Laurenta121f902014-06-03 13:32:54 -07006726 if (mGains.size() > 0) {
6727 mGains[0]->getDefaultConfig(&mGain);
6728 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006729}
6730
Eric Laurent3a4311c2014-03-17 12:00:47 -07006731bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006732{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006733 // Devices are considered equal if they:
6734 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6735 // - have the same address or one device does not specify the address
6736 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006737 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006738 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006739 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006740 mChannelMask == other->mChannelMask);
6741}
6742
6743void AudioPolicyManager::DeviceVector::refreshTypes()
6744{
Eric Laurent1c333e22014-05-20 10:48:17 -07006745 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006746 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006747 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006748 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006749 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006750}
6751
6752ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6753{
6754 for(size_t i = 0; i < size(); i++) {
6755 if (item->equals(itemAt(i))) {
6756 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006757 }
6758 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006759 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006760}
6761
Eric Laurent3a4311c2014-03-17 12:00:47 -07006762ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006763{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006764 ssize_t ret = indexOf(item);
6765
6766 if (ret < 0) {
6767 ret = SortedVector::add(item);
6768 if (ret >= 0) {
6769 refreshTypes();
6770 }
6771 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006772 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006773 ret = -1;
6774 }
6775 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006776}
6777
Eric Laurent3a4311c2014-03-17 12:00:47 -07006778ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6779{
6780 size_t i;
6781 ssize_t ret = indexOf(item);
6782
6783 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006784 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006785 } else {
6786 ret = SortedVector::removeAt(ret);
6787 if (ret >= 0) {
6788 refreshTypes();
6789 }
6790 }
6791 return ret;
6792}
6793
6794void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6795{
6796 DeviceVector deviceList;
6797
6798 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6799 types &= ~role_bit;
6800
6801 while (types) {
6802 uint32_t i = 31 - __builtin_clz(types);
6803 uint32_t type = 1 << i;
6804 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006805 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006806 }
6807}
6808
Eric Laurent1afeecb2014-05-14 08:52:28 -07006809void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6810 const DeviceVector& declaredDevices)
6811{
6812 char *devName = strtok(name, "|");
6813 while (devName != NULL) {
6814 if (strlen(devName) != 0) {
6815 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6816 ARRAY_SIZE(sDeviceNameToEnumTable),
6817 devName);
6818 if (type != AUDIO_DEVICE_NONE) {
6819 add(new DeviceDescriptor(String8(""), type));
6820 } else {
6821 sp<DeviceDescriptor> deviceDesc =
6822 declaredDevices.getDeviceFromName(String8(devName));
6823 if (deviceDesc != 0) {
6824 add(deviceDesc);
6825 }
6826 }
6827 }
6828 devName = strtok(NULL, "|");
6829 }
6830}
6831
Eric Laurent1c333e22014-05-20 10:48:17 -07006832sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6833 audio_devices_t type, String8 address) const
6834{
6835 sp<DeviceDescriptor> device;
6836 for (size_t i = 0; i < size(); i++) {
6837 if (itemAt(i)->mDeviceType == type) {
6838 device = itemAt(i);
6839 if (itemAt(i)->mAddress = address) {
6840 break;
6841 }
6842 }
6843 }
6844 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6845 type, address.string(), device.get());
6846 return device;
6847}
6848
Eric Laurent6a94d692014-05-20 11:18:06 -07006849sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6850 audio_port_handle_t id) const
6851{
6852 sp<DeviceDescriptor> device;
6853 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006854 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006855 if (itemAt(i)->mId == id) {
6856 device = itemAt(i);
6857 break;
6858 }
6859 }
6860 return device;
6861}
6862
Eric Laurent1c333e22014-05-20 10:48:17 -07006863AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6864 audio_devices_t type) const
6865{
6866 DeviceVector devices;
6867 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6868 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6869 devices.add(itemAt(i));
6870 type &= ~itemAt(i)->mDeviceType;
6871 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6872 itemAt(i)->mDeviceType, itemAt(i).get());
6873 }
6874 }
6875 return devices;
6876}
6877
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006878AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6879 audio_devices_t type, String8 address) const
6880{
6881 DeviceVector devices;
6882 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6883 for (size_t i = 0; i < size(); i++) {
6884 //ALOGV(" at i=%d: device=%x, addr=%s",
6885 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6886 if (itemAt(i)->mDeviceType == type) {
6887 if (itemAt(i)->mAddress == address) {
6888 //ALOGV(" found matching address %s", address.string());
6889 devices.add(itemAt(i));
6890 }
6891 }
6892 }
6893 return devices;
6894}
6895
Eric Laurent1afeecb2014-05-14 08:52:28 -07006896sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6897 const String8& name) const
6898{
6899 sp<DeviceDescriptor> device;
6900 for (size_t i = 0; i < size(); i++) {
6901 if (itemAt(i)->mName == name) {
6902 device = itemAt(i);
6903 break;
6904 }
6905 }
6906 return device;
6907}
6908
Eric Laurent6a94d692014-05-20 11:18:06 -07006909void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6910 struct audio_port_config *dstConfig,
6911 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006912{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006913 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6914 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006915 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006916 }
6917
6918 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6919
Eric Laurent6a94d692014-05-20 11:18:06 -07006920 dstConfig->id = mId;
6921 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006922 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006923 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006924 dstConfig->ext.device.type = mDeviceType;
6925 dstConfig->ext.device.hw_module = mModule->mHandle;
6926 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006927}
6928
6929void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6930{
Eric Laurent83b88082014-06-20 18:31:16 -07006931 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006932 AudioPort::toAudioPort(port);
6933 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006934 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006935 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006936 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006937 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6938}
6939
Eric Laurent1afeecb2014-05-14 08:52:28 -07006940status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006941{
6942 const size_t SIZE = 256;
6943 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006944 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006945
Eric Laurent1afeecb2014-05-14 08:52:28 -07006946 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6947 result.append(buffer);
6948 if (mId != 0) {
6949 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6950 result.append(buffer);
6951 }
6952 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6953 enumToString(sDeviceNameToEnumTable,
6954 ARRAY_SIZE(sDeviceNameToEnumTable),
6955 mDeviceType));
6956 result.append(buffer);
6957 if (mAddress.size() != 0) {
6958 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6959 result.append(buffer);
6960 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006961 write(fd, result.string(), result.size());
6962 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006963
6964 return NO_ERROR;
6965}
6966
Eric Laurent4d416952014-08-10 14:07:09 -07006967status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
6968{
6969 const size_t SIZE = 256;
6970 char buffer[SIZE];
6971 String8 result;
6972
6973
6974 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
6975 result.append(buffer);
6976 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
6977 result.append(buffer);
6978 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
6979 result.append(buffer);
6980 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
6981 result.append(buffer);
6982 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
6983 result.append(buffer);
6984 for (size_t i = 0; i < mPatch.num_sources; i++) {
6985 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
6986 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
6987 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
6988 ARRAY_SIZE(sDeviceNameToEnumTable),
6989 mPatch.sources[i].ext.device.type));
6990 } else {
6991 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
6992 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
6993 }
6994 result.append(buffer);
6995 }
6996 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
6997 result.append(buffer);
6998 for (size_t i = 0; i < mPatch.num_sinks; i++) {
6999 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7000 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7001 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7002 ARRAY_SIZE(sDeviceNameToEnumTable),
7003 mPatch.sinks[i].ext.device.type));
7004 } else {
7005 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7006 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7007 }
7008 result.append(buffer);
7009 }
7010
7011 write(fd, result.string(), result.size());
7012 return NO_ERROR;
7013}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007014
7015// --- audio_policy.conf file parsing
7016
Eric Laurent5dbe4712014-09-19 19:04:57 -07007017uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007018{
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) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007026 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7027 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007028 flagName);
7029 }
7030 flagName = strtok(NULL, "|");
7031 }
7032 //force direct flag if offload flag is set: offloading implies a direct output stream
7033 // and all common behaviors are driven by checking only the direct flag
7034 // this should normally be set appropriately in the policy configuration file
7035 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7036 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7037 }
7038
Eric Laurent5dbe4712014-09-19 19:04:57 -07007039 return flag;
7040}
7041
7042uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7043{
7044 uint32_t flag = 0;
7045
7046 // it is OK to cast name to non const here as we are not going to use it after
7047 // strtok() modifies it
7048 char *flagName = strtok(name, "|");
7049 while (flagName != NULL) {
7050 if (strlen(flagName) != 0) {
7051 flag |= stringToEnum(sInputFlagNameToEnumTable,
7052 ARRAY_SIZE(sInputFlagNameToEnumTable),
7053 flagName);
7054 }
7055 flagName = strtok(NULL, "|");
7056 }
7057 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007058}
7059
Eric Laurente0720872014-03-11 09:30:41 -07007060audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007061{
7062 uint32_t device = 0;
7063
7064 char *devName = strtok(name, "|");
7065 while (devName != NULL) {
7066 if (strlen(devName) != 0) {
7067 device |= stringToEnum(sDeviceNameToEnumTable,
7068 ARRAY_SIZE(sDeviceNameToEnumTable),
7069 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007070 }
Eric Laurente552edb2014-03-10 17:42:56 -07007071 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007072 }
Eric Laurente552edb2014-03-10 17:42:56 -07007073 return device;
7074}
7075
Eric Laurente0720872014-03-11 09:30:41 -07007076void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007077{
Eric Laurente552edb2014-03-10 17:42:56 -07007078 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007079 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007080 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007081
Eric Laurent1afeecb2014-05-14 08:52:28 -07007082 node = config_find(root, DEVICES_TAG);
7083 if (node != NULL) {
7084 node = node->first_child;
7085 while (node) {
7086 ALOGV("loadHwModule() loading device %s", node->name);
7087 status_t tmpStatus = module->loadDevice(node);
7088 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7089 status = tmpStatus;
7090 }
7091 node = node->next;
7092 }
7093 }
7094 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007095 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007096 node = node->first_child;
7097 while (node) {
7098 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007099 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007100 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7101 status = tmpStatus;
7102 }
7103 node = node->next;
7104 }
7105 }
7106 node = config_find(root, INPUTS_TAG);
7107 if (node != NULL) {
7108 node = node->first_child;
7109 while (node) {
7110 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007111 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007112 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7113 status = tmpStatus;
7114 }
7115 node = node->next;
7116 }
7117 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007118 loadGlobalConfig(root, module);
7119
Eric Laurente552edb2014-03-10 17:42:56 -07007120 if (status == NO_ERROR) {
7121 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007122 }
7123}
7124
Eric Laurente0720872014-03-11 09:30:41 -07007125void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007126{
7127 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7128 if (node == NULL) {
7129 return;
7130 }
7131
7132 node = node->first_child;
7133 while (node) {
7134 ALOGV("loadHwModules() loading module %s", node->name);
7135 loadHwModule(node);
7136 node = node->next;
7137 }
7138}
7139
Eric Laurent1f2f2232014-06-02 12:01:23 -07007140void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007141{
7142 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007143
Eric Laurente552edb2014-03-10 17:42:56 -07007144 if (node == NULL) {
7145 return;
7146 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007147 DeviceVector declaredDevices;
7148 if (module != NULL) {
7149 declaredDevices = module->mDeclaredDevices;
7150 }
7151
Eric Laurente552edb2014-03-10 17:42:56 -07007152 node = node->first_child;
7153 while (node) {
7154 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007155 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7156 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007157 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7158 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007159 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007160 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007161 ARRAY_SIZE(sDeviceNameToEnumTable),
7162 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007163 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007164 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007165 } else {
7166 ALOGW("loadGlobalConfig() default device not specified");
7167 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007168 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007169 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007170 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7171 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007172 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007173 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7174 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7175 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007176 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7177 uint32_t major, minor;
7178 sscanf((char *)node->value, "%u.%u", &major, &minor);
7179 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7180 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7181 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007182 }
7183 node = node->next;
7184 }
7185}
7186
Eric Laurente0720872014-03-11 09:30:41 -07007187status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007188{
7189 cnode *root;
7190 char *data;
7191
7192 data = (char *)load_file(path, NULL);
7193 if (data == NULL) {
7194 return -ENODEV;
7195 }
7196 root = config_node("", "");
7197 config_load(root, data);
7198
Eric Laurente552edb2014-03-10 17:42:56 -07007199 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007200 // legacy audio_policy.conf files have one global_configuration section
7201 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007202 config_free(root);
7203 free(root);
7204 free(data);
7205
7206 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7207
7208 return NO_ERROR;
7209}
7210
Eric Laurente0720872014-03-11 09:30:41 -07007211void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007212{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007213 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007214 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007215 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7216 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007217 mAvailableOutputDevices.add(mDefaultOutputDevice);
7218 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007219
7220 module = new HwModule("primary");
7221
Eric Laurent1afeecb2014-05-14 08:52:28 -07007222 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007223 profile->mSamplingRates.add(44100);
7224 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7225 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007226 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007227 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7228 module->mOutputProfiles.add(profile);
7229
Eric Laurent1afeecb2014-05-14 08:52:28 -07007230 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007231 profile->mSamplingRates.add(8000);
7232 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7233 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007234 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007235 module->mInputProfiles.add(profile);
7236
7237 mHwModules.add(module);
7238}
7239
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07007240audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
7241{
7242 // flags to stream type mapping
7243 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
7244 return AUDIO_STREAM_ENFORCED_AUDIBLE;
7245 }
7246 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
7247 return AUDIO_STREAM_BLUETOOTH_SCO;
7248 }
7249
7250 // usage to stream type mapping
7251 switch (attr->usage) {
7252 case AUDIO_USAGE_MEDIA:
7253 case AUDIO_USAGE_GAME:
7254 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7255 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7256 return AUDIO_STREAM_MUSIC;
7257 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7258 return AUDIO_STREAM_SYSTEM;
7259 case AUDIO_USAGE_VOICE_COMMUNICATION:
7260 return AUDIO_STREAM_VOICE_CALL;
7261
7262 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7263 return AUDIO_STREAM_DTMF;
7264
7265 case AUDIO_USAGE_ALARM:
7266 return AUDIO_STREAM_ALARM;
7267 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7268 return AUDIO_STREAM_RING;
7269
7270 case AUDIO_USAGE_NOTIFICATION:
7271 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7272 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7273 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7274 case AUDIO_USAGE_NOTIFICATION_EVENT:
7275 return AUDIO_STREAM_NOTIFICATION;
7276
7277 case AUDIO_USAGE_UNKNOWN:
7278 default:
7279 return AUDIO_STREAM_MUSIC;
7280 }
7281}
Eric Laurente552edb2014-03-10 17:42:56 -07007282}; // namespace android