1 /*
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
17 #define LOG_TAG "APM_AudioPolicyManager"
18 //#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 #define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28 #define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
29
30 #include <inttypes.h>
31 #include <math.h>
32
33 #include <AudioPolicyManagerInterface.h>
34 #include <AudioPolicyEngineInstance.h>
35 #include <cutils/atomic.h>
36 #include <cutils/properties.h>
37 #include <utils/Log.h>
38 #include <media/AudioParameter.h>
39 #include <media/AudioPolicyHelper.h>
40 #include <soundtrigger/SoundTrigger.h>
41 #include <system/audio.h>
42 #include <audio_policy_conf.h>
43 #include "AudioPolicyManager.h"
44 #ifndef USE_XML_AUDIO_POLICY_CONF
45 #include <ConfigParsingUtils.h>
46 #include <StreamDescriptor.h>
47 #endif
48 #include <Serializer.h>
49 #include "TypeConverter.h"
50 #include <policy.h>
51
52 namespace android {
53
54 //FIXME: workaround for truncated touch sounds
55 // to be removed when the problem is handled by system UI
56 #define TOUCH_SOUND_FIXED_DELAY_MS 100
57
58 // Largest difference in dB on earpiece in call between the voice volume and another
59 // media / notification / system volume.
60 constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
61
62 // ----------------------------------------------------------------------------
63 // AudioPolicyInterface implementation
64 // ----------------------------------------------------------------------------
65
setDeviceConnectionState(audio_devices_t device,audio_policy_dev_state_t state,const char * device_address,const char * device_name)66 status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
67 audio_policy_dev_state_t state,
68 const char *device_address,
69 const char *device_name)
70 {
71 return setDeviceConnectionStateInt(device, state, device_address, device_name);
72 }
73
broadcastDeviceConnectionState(audio_devices_t device,audio_policy_dev_state_t state,const String8 & device_address)74 void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
75 audio_policy_dev_state_t state,
76 const String8 &device_address)
77 {
78 AudioParameter param(device_address);
79 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
80 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
81 param.addInt(key, device);
82 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
83 }
84
setDeviceConnectionStateInt(audio_devices_t device,audio_policy_dev_state_t state,const char * device_address,const char * device_name)85 status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
86 audio_policy_dev_state_t state,
87 const char *device_address,
88 const char *device_name)
89 {
90 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
91 - device, state, device_address, device_name);
92
93 // connect/disconnect only 1 device at a time
94 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
95
96 sp<DeviceDescriptor> devDesc =
97 mHwModules.getDeviceDescriptor(device, device_address, device_name);
98
99 // handle output devices
100 if (audio_is_output_device(device)) {
101 SortedVector <audio_io_handle_t> outputs;
102
103 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
104
105 // save a copy of the opened output descriptors before any output is opened or closed
106 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
107 mPreviousOutputs = mOutputs;
108 switch (state)
109 {
110 // handle output device connection
111 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
112 if (index >= 0) {
113 ALOGW("setDeviceConnectionState() device already connected: %x", device);
114 return INVALID_OPERATION;
115 }
116 ALOGV("setDeviceConnectionState() connecting device %x", device);
117
118 // register new device as available
119 index = mAvailableOutputDevices.add(devDesc);
120 if (index >= 0) {
121 sp<HwModule> module = mHwModules.getModuleForDevice(device);
122 if (module == 0) {
123 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
124 device);
125 mAvailableOutputDevices.remove(devDesc);
126 return INVALID_OPERATION;
127 }
128 mAvailableOutputDevices[index]->attach(module);
129 } else {
130 return NO_MEMORY;
131 }
132
133 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
134 // parameters on newly connected devices (instead of opening the outputs...)
135 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
136
137 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
138 mAvailableOutputDevices.remove(devDesc);
139
140 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
141 devDesc->mAddress);
142 return INVALID_OPERATION;
143 }
144 // Propagate device availability to Engine
145 mEngine->setDeviceConnectionState(devDesc, state);
146
147 // outputs should never be empty here
148 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
149 "checkOutputsForDevice() returned no outputs but status OK");
150 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
151 outputs.size());
152
153 } break;
154 // handle output device disconnection
155 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
156 if (index < 0) {
157 ALOGW("setDeviceConnectionState() device not connected: %x", device);
158 return INVALID_OPERATION;
159 }
160
161 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
162
163 // Send Disconnect to HALs
164 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
165
166 // remove device from available output devices
167 mAvailableOutputDevices.remove(devDesc);
168
169 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
170
171 // Propagate device availability to Engine
172 mEngine->setDeviceConnectionState(devDesc, state);
173 } break;
174
175 default:
176 ALOGE("setDeviceConnectionState() invalid state: %x", state);
177 return BAD_VALUE;
178 }
179
180 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
181 // output is suspended before any tracks are moved to it
182 checkA2dpSuspend();
183 checkOutputForAllStrategies();
184 // outputs must be closed after checkOutputForAllStrategies() is executed
185 if (!outputs.isEmpty()) {
186 for (size_t i = 0; i < outputs.size(); i++) {
187 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
188 // close unused outputs after device disconnection or direct outputs that have been
189 // opened by checkOutputsForDevice() to query dynamic parameters
190 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
191 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
192 (desc->mDirectOpenCount == 0))) {
193 closeOutput(outputs[i]);
194 }
195 }
196 // check again after closing A2DP output to reset mA2dpSuspended if needed
197 checkA2dpSuspend();
198 }
199
200 updateDevicesAndOutputs();
201 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
202 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
203 updateCallRouting(newDevice);
204 }
205 for (size_t i = 0; i < mOutputs.size(); i++) {
206 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
207 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
208 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
209 // do not force device change on duplicated output because if device is 0, it will
210 // also force a device 0 for the two outputs it is duplicated to which may override
211 // a valid device selection on those outputs.
212 bool force = !desc->isDuplicated()
213 && (!device_distinguishes_on_address(device)
214 // always force when disconnecting (a non-duplicated device)
215 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
216 setOutputDevice(desc, newDevice, force, 0);
217 }
218 }
219
220 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
221 cleanUpForDevice(devDesc);
222 }
223
224 mpClientInterface->onAudioPortListUpdate();
225 return NO_ERROR;
226 } // end if is output device
227
228 // handle input devices
229 if (audio_is_input_device(device)) {
230 SortedVector <audio_io_handle_t> inputs;
231
232 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
233 switch (state)
234 {
235 // handle input device connection
236 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
237 if (index >= 0) {
238 ALOGW("setDeviceConnectionState() device already connected: %d", device);
239 return INVALID_OPERATION;
240 }
241 sp<HwModule> module = mHwModules.getModuleForDevice(device);
242 if (module == NULL) {
243 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
244 device);
245 return INVALID_OPERATION;
246 }
247
248 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
249 // parameters on newly connected devices (instead of opening the inputs...)
250 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
251
252 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
253 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
254 devDesc->mAddress);
255 return INVALID_OPERATION;
256 }
257
258 index = mAvailableInputDevices.add(devDesc);
259 if (index >= 0) {
260 mAvailableInputDevices[index]->attach(module);
261 } else {
262 return NO_MEMORY;
263 }
264
265 // Propagate device availability to Engine
266 mEngine->setDeviceConnectionState(devDesc, state);
267 } break;
268
269 // handle input device disconnection
270 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
271 if (index < 0) {
272 ALOGW("setDeviceConnectionState() device not connected: %d", device);
273 return INVALID_OPERATION;
274 }
275
276 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
277
278 // Set Disconnect to HALs
279 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
280
281 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
282 mAvailableInputDevices.remove(devDesc);
283
284 // Propagate device availability to Engine
285 mEngine->setDeviceConnectionState(devDesc, state);
286 } break;
287
288 default:
289 ALOGE("setDeviceConnectionState() invalid state: %x", state);
290 return BAD_VALUE;
291 }
292
293 closeAllInputs();
294 // As the input device list can impact the output device selection, update
295 // getDeviceForStrategy() cache
296 updateDevicesAndOutputs();
297
298 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
299 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
300 updateCallRouting(newDevice);
301 }
302
303 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
304 cleanUpForDevice(devDesc);
305 }
306
307 mpClientInterface->onAudioPortListUpdate();
308 return NO_ERROR;
309 } // end if is input device
310
311 ALOGW("setDeviceConnectionState() invalid device: %x", device);
312 return BAD_VALUE;
313 }
314
getDeviceConnectionState(audio_devices_t device,const char * device_address)315 audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
316 const char *device_address)
317 {
318 sp<DeviceDescriptor> devDesc =
319 mHwModules.getDeviceDescriptor(device, device_address, "",
320 (strlen(device_address) != 0)/*matchAddress*/);
321
322 if (devDesc == 0) {
323 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
324 device, device_address);
325 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
326 }
327
328 DeviceVector *deviceVector;
329
330 if (audio_is_output_device(device)) {
331 deviceVector = &mAvailableOutputDevices;
332 } else if (audio_is_input_device(device)) {
333 deviceVector = &mAvailableInputDevices;
334 } else {
335 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
336 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
337 }
338
339 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
340 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
341 }
342
handleDeviceConfigChange(audio_devices_t device,const char * device_address,const char * device_name)343 status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
344 const char *device_address,
345 const char *device_name)
346 {
347 status_t status;
348
349 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
350 device, device_address, device_name);
351
352 // connect/disconnect only 1 device at a time
353 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
354
355 // Check if the device is currently connected
356 sp<DeviceDescriptor> devDesc =
357 mHwModules.getDeviceDescriptor(device, device_address, device_name);
358 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
359 if (index < 0) {
360 // Nothing to do: device is not connected
361 return NO_ERROR;
362 }
363
364 // Toggle the device state: UNAVAILABLE -> AVAILABLE
365 // This will force reading again the device configuration
366 status = setDeviceConnectionState(device,
367 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
368 device_address, device_name);
369 if (status != NO_ERROR) {
370 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
371 status);
372 return status;
373 }
374
375 status = setDeviceConnectionState(device,
376 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
377 device_address, device_name);
378 if (status != NO_ERROR) {
379 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
380 status);
381 return status;
382 }
383
384 return NO_ERROR;
385 }
386
updateCallRouting(audio_devices_t rxDevice,uint32_t delayMs)387 uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
388 {
389 bool createTxPatch = false;
390 status_t status;
391 audio_patch_handle_t afPatchHandle;
392 DeviceVector deviceList;
393 uint32_t muteWaitMs = 0;
394
395 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
396 return muteWaitMs;
397 }
398 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
399 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
400
401 // release existing RX patch if any
402 if (mCallRxPatch != 0) {
403 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
404 mCallRxPatch.clear();
405 }
406 // release TX patch if any
407 if (mCallTxPatch != 0) {
408 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
409 mCallTxPatch.clear();
410 }
411
412 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
413 // via setOutputDevice() on primary output.
414 // Otherwise, create two audio patches for TX and RX path.
415 if (availablePrimaryOutputDevices() & rxDevice) {
416 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
417 // If the TX device is also on the primary HW module, setOutputDevice() will take care
418 // of it due to legacy implementation. If not, create a patch.
419 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
420 == AUDIO_DEVICE_NONE) {
421 createTxPatch = true;
422 }
423 } else { // create RX path audio patch
424 struct audio_patch patch;
425
426 patch.num_sources = 1;
427 patch.num_sinks = 1;
428 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
429 ALOG_ASSERT(!deviceList.isEmpty(),
430 "updateCallRouting() selected device not in output device list");
431 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
432 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
433 ALOG_ASSERT(!deviceList.isEmpty(),
434 "updateCallRouting() no telephony RX device");
435 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
436
437 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
438 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
439
440 // request to reuse existing output stream if one is already opened to reach the RX device
441 SortedVector<audio_io_handle_t> outputs =
442 getOutputsForDevice(rxDevice, mOutputs);
443 audio_io_handle_t output = selectOutput(outputs,
444 AUDIO_OUTPUT_FLAG_NONE,
445 AUDIO_FORMAT_INVALID);
446 if (output != AUDIO_IO_HANDLE_NONE) {
447 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
448 ALOG_ASSERT(!outputDesc->isDuplicated(),
449 "updateCallRouting() RX device output is duplicated");
450 outputDesc->toAudioPortConfig(&patch.sources[1]);
451 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
452 patch.num_sources = 2;
453 }
454
455 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
456 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
457 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
458 status);
459 if (status == NO_ERROR) {
460 mCallRxPatch = new AudioPatch(&patch, mUidCached);
461 mCallRxPatch->mAfPatchHandle = afPatchHandle;
462 mCallRxPatch->mUid = mUidCached;
463 }
464 createTxPatch = true;
465 }
466 if (createTxPatch) { // create TX path audio patch
467 struct audio_patch patch;
468
469 patch.num_sources = 1;
470 patch.num_sinks = 1;
471 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
472 ALOG_ASSERT(!deviceList.isEmpty(),
473 "updateCallRouting() selected device not in input device list");
474 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
475 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
476 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
477 ALOG_ASSERT(!deviceList.isEmpty(),
478 "updateCallRouting() no telephony TX device");
479 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
480 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
481
482 SortedVector<audio_io_handle_t> outputs =
483 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
484 audio_io_handle_t output = selectOutput(outputs,
485 AUDIO_OUTPUT_FLAG_NONE,
486 AUDIO_FORMAT_INVALID);
487 // request to reuse existing output stream if one is already opened to reach the TX
488 // path output device
489 if (output != AUDIO_IO_HANDLE_NONE) {
490 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
491 ALOG_ASSERT(!outputDesc->isDuplicated(),
492 "updateCallRouting() RX device output is duplicated");
493 outputDesc->toAudioPortConfig(&patch.sources[1]);
494 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
495 patch.num_sources = 2;
496 }
497
498 // terminate active capture if on the same HW module as the call TX source device
499 // FIXME: would be better to refine to only inputs whose profile connects to the
500 // call TX device but this information is not in the audio patch and logic here must be
501 // symmetric to the one in startInput()
502 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
503 for (size_t i = 0; i < activeInputs.size(); i++) {
504 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
505 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
506 AudioSessionCollection activeSessions =
507 activeDesc->getAudioSessions(true /*activeOnly*/);
508 for (size_t j = 0; j < activeSessions.size(); j++) {
509 audio_session_t activeSession = activeSessions.keyAt(j);
510 stopInput(activeDesc->mIoHandle, activeSession);
511 releaseInput(activeDesc->mIoHandle, activeSession);
512 }
513 }
514 }
515
516 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
517 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
518 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
519 status);
520 if (status == NO_ERROR) {
521 mCallTxPatch = new AudioPatch(&patch, mUidCached);
522 mCallTxPatch->mAfPatchHandle = afPatchHandle;
523 mCallTxPatch->mUid = mUidCached;
524 }
525 }
526
527 return muteWaitMs;
528 }
529
setPhoneState(audio_mode_t state)530 void AudioPolicyManager::setPhoneState(audio_mode_t state)
531 {
532 ALOGV("setPhoneState() state %d", state);
533 // store previous phone state for management of sonification strategy below
534 int oldState = mEngine->getPhoneState();
535
536 if (mEngine->setPhoneState(state) != NO_ERROR) {
537 ALOGW("setPhoneState() invalid or same state %d", state);
538 return;
539 }
540 /// Opens: can these line be executed after the switch of volume curves???
541 // if leaving call state, handle special case of active streams
542 // pertaining to sonification strategy see handleIncallSonification()
543 if (isStateInCall(oldState)) {
544 ALOGV("setPhoneState() in call state management: new state is %d", state);
545 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
546 handleIncallSonification((audio_stream_type_t)stream, false, true);
547 }
548
549 // force reevaluating accessibility routing when call stops
550 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
551 }
552
553 /**
554 * Switching to or from incall state or switching between telephony and VoIP lead to force
555 * routing command.
556 */
557 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
558 || (is_state_in_call(state) && (state != oldState)));
559
560 // check for device and output changes triggered by new phone state
561 checkA2dpSuspend();
562 checkOutputForAllStrategies();
563 updateDevicesAndOutputs();
564
565 int delayMs = 0;
566 if (isStateInCall(state)) {
567 nsecs_t sysTime = systemTime();
568 for (size_t i = 0; i < mOutputs.size(); i++) {
569 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
570 // mute media and sonification strategies and delay device switch by the largest
571 // latency of any output where either strategy is active.
572 // This avoid sending the ring tone or music tail into the earpiece or headset.
573 if ((isStrategyActive(desc, STRATEGY_MEDIA,
574 SONIFICATION_HEADSET_MUSIC_DELAY,
575 sysTime) ||
576 isStrategyActive(desc, STRATEGY_SONIFICATION,
577 SONIFICATION_HEADSET_MUSIC_DELAY,
578 sysTime)) &&
579 (delayMs < (int)desc->latency()*2)) {
580 delayMs = desc->latency()*2;
581 }
582 setStrategyMute(STRATEGY_MEDIA, true, desc);
583 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
584 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
585 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
586 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
587 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
588 }
589 }
590
591 if (hasPrimaryOutput()) {
592 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
593 // the device returned is not necessarily reachable via this output
594 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
595 // force routing command to audio hardware when ending call
596 // even if no device change is needed
597 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
598 rxDevice = mPrimaryOutput->device();
599 }
600
601 if (state == AUDIO_MODE_IN_CALL) {
602 updateCallRouting(rxDevice, delayMs);
603 } else if (oldState == AUDIO_MODE_IN_CALL) {
604 if (mCallRxPatch != 0) {
605 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
606 mCallRxPatch.clear();
607 }
608 if (mCallTxPatch != 0) {
609 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
610 mCallTxPatch.clear();
611 }
612 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
613 } else {
614 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
615 }
616 }
617 // if entering in call state, handle special case of active streams
618 // pertaining to sonification strategy see handleIncallSonification()
619 if (isStateInCall(state)) {
620 ALOGV("setPhoneState() in call state management: new state is %d", state);
621 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
622 handleIncallSonification((audio_stream_type_t)stream, true, true);
623 }
624
625 // force reevaluating accessibility routing when call starts
626 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
627 }
628
629 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
630 if (state == AUDIO_MODE_RINGTONE &&
631 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
632 mLimitRingtoneVolume = true;
633 } else {
634 mLimitRingtoneVolume = false;
635 }
636 }
637
getPhoneState()638 audio_mode_t AudioPolicyManager::getPhoneState() {
639 return mEngine->getPhoneState();
640 }
641
setForceUse(audio_policy_force_use_t usage,audio_policy_forced_cfg_t config)642 void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
643 audio_policy_forced_cfg_t config)
644 {
645 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
646 if (config == mEngine->getForceUse(usage)) {
647 return;
648 }
649
650 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
651 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
652 return;
653 }
654 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
655 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
656 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
657
658 // check for device and output changes triggered by new force usage
659 checkA2dpSuspend();
660 checkOutputForAllStrategies();
661 updateDevicesAndOutputs();
662
663 //FIXME: workaround for truncated touch sounds
664 // to be removed when the problem is handled by system UI
665 uint32_t delayMs = 0;
666 uint32_t waitMs = 0;
667 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
668 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
669 }
670 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
671 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
672 waitMs = updateCallRouting(newDevice, delayMs);
673 }
674 for (size_t i = 0; i < mOutputs.size(); i++) {
675 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
676 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
677 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
678 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
679 delayMs);
680 }
681 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
682 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
683 }
684 }
685
686 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
687 for (size_t i = 0; i < activeInputs.size(); i++) {
688 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
689 audio_devices_t newDevice = getNewInputDevice(activeDesc);
690 // Force new input selection if the new device can not be reached via current input
691 if (activeDesc->mProfile->getSupportedDevices().types() &
692 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
693 setInputDevice(activeDesc->mIoHandle, newDevice);
694 } else {
695 closeInput(activeDesc->mIoHandle);
696 }
697 }
698 }
699
setSystemProperty(const char * property,const char * value)700 void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
701 {
702 ALOGV("setSystemProperty() property %s, value %s", property, value);
703 }
704
705 // Find a direct output profile compatible with the parameters passed, even if the input flags do
706 // not explicitly request a direct output
getProfileForDirectOutput(audio_devices_t device,uint32_t samplingRate,audio_format_t format,audio_channel_mask_t channelMask,audio_output_flags_t flags)707 sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
708 audio_devices_t device,
709 uint32_t samplingRate,
710 audio_format_t format,
711 audio_channel_mask_t channelMask,
712 audio_output_flags_t flags)
713 {
714 // only retain flags that will drive the direct output profile selection
715 // if explicitly requested
716 static const uint32_t kRelevantFlags =
717 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
718 AUDIO_OUTPUT_FLAG_VOIP_RX);
719 flags =
720 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
721
722 sp<IOProfile> profile;
723
724 for (size_t i = 0; i < mHwModules.size(); i++) {
725 if (mHwModules[i]->mHandle == 0) {
726 continue;
727 }
728 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
729 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
730 if (!curProfile->isCompatibleProfile(device, String8(""),
731 samplingRate, NULL /*updatedSamplingRate*/,
732 format, NULL /*updatedFormat*/,
733 channelMask, NULL /*updatedChannelMask*/,
734 flags)) {
735 continue;
736 }
737 // reject profiles not corresponding to a device currently available
738 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
739 continue;
740 }
741 // if several profiles are compatible, give priority to one with offload capability
742 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
743 continue;
744 }
745 profile = curProfile;
746 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
747 break;
748 }
749 }
750 }
751 return profile;
752 }
753
getOutput(audio_stream_type_t stream,uint32_t samplingRate,audio_format_t format,audio_channel_mask_t channelMask,audio_output_flags_t flags,const audio_offload_info_t * offloadInfo)754 audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
755 uint32_t samplingRate,
756 audio_format_t format,
757 audio_channel_mask_t channelMask,
758 audio_output_flags_t flags,
759 const audio_offload_info_t *offloadInfo)
760 {
761 routing_strategy strategy = getStrategy(stream);
762 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
763 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
764 device, stream, samplingRate, format, channelMask, flags);
765
766 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE, stream, samplingRate, format,
767 channelMask, flags, offloadInfo);
768 }
769
getOutputForAttr(const audio_attributes_t * attr,audio_io_handle_t * output,audio_session_t session,audio_stream_type_t * stream,uid_t uid,const audio_config_t * config,audio_output_flags_t flags,audio_port_handle_t * selectedDeviceId,audio_port_handle_t * portId)770 status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
771 audio_io_handle_t *output,
772 audio_session_t session,
773 audio_stream_type_t *stream,
774 uid_t uid,
775 const audio_config_t *config,
776 audio_output_flags_t flags,
777 audio_port_handle_t *selectedDeviceId,
778 audio_port_handle_t *portId)
779 {
780 audio_attributes_t attributes;
781 if (attr != NULL) {
782 if (!isValidAttributes(attr)) {
783 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
784 attr->usage, attr->content_type, attr->flags,
785 attr->tags);
786 return BAD_VALUE;
787 }
788 attributes = *attr;
789 } else {
790 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
791 ALOGE("getOutputForAttr(): invalid stream type");
792 return BAD_VALUE;
793 }
794 stream_type_to_audio_attributes(*stream, &attributes);
795 }
796
797 // TODO: check for existing client for this port ID
798 if (*portId == AUDIO_PORT_HANDLE_NONE) {
799 *portId = AudioPort::getNextUniqueId();
800 }
801
802 sp<SwAudioOutputDescriptor> desc;
803 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
804 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
805 if (!audio_has_proportional_frames(config->format)) {
806 return BAD_VALUE;
807 }
808 *stream = streamTypefromAttributesInt(&attributes);
809 *output = desc->mIoHandle;
810 ALOGV("getOutputForAttr() returns output %d", *output);
811 return NO_ERROR;
812 }
813 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
814 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
815 return BAD_VALUE;
816 }
817
818 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
819 " session %d selectedDeviceId %d",
820 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
821 session, *selectedDeviceId);
822
823 *stream = streamTypefromAttributesInt(&attributes);
824
825 // Explicit routing?
826 sp<DeviceDescriptor> deviceDesc;
827 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
828 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
829 if (mAvailableOutputDevices[i]->getId() == *selectedDeviceId) {
830 deviceDesc = mAvailableOutputDevices[i];
831 break;
832 }
833 }
834 }
835 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
836
837 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
838 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
839
840 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
841 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
842 }
843
844 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
845 device, config->sample_rate, config->format, config->channel_mask, flags);
846
847 *output = getOutputForDevice(device, session, *stream,
848 config->sample_rate, config->format, config->channel_mask,
849 flags, &config->offload_info);
850 if (*output == AUDIO_IO_HANDLE_NONE) {
851 mOutputRoutes.removeRoute(session);
852 return INVALID_OPERATION;
853 }
854
855 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
856 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
857 : AUDIO_PORT_HANDLE_NONE;
858
859 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
860
861 return NO_ERROR;
862 }
863
getOutputForDevice(audio_devices_t device,audio_session_t session,audio_stream_type_t stream,uint32_t samplingRate,audio_format_t format,audio_channel_mask_t channelMask,audio_output_flags_t flags,const audio_offload_info_t * offloadInfo)864 audio_io_handle_t AudioPolicyManager::getOutputForDevice(
865 audio_devices_t device,
866 audio_session_t session,
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 {
874 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
875 status_t status;
876
877 #ifdef AUDIO_POLICY_TEST
878 if (mCurOutput != 0) {
879 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
880 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
881
882 if (mTestOutputs[mCurOutput] == 0) {
883 ALOGV("getOutput() opening test output");
884 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
885 mpClientInterface);
886 outputDesc->mDevice = mTestDevice;
887 outputDesc->mLatency = mTestLatencyMs;
888 outputDesc->mFlags =
889 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
890 outputDesc->mRefCount[stream] = 0;
891 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
892 config.sample_rate = mTestSamplingRate;
893 config.channel_mask = mTestChannels;
894 config.format = mTestFormat;
895 if (offloadInfo != NULL) {
896 config.offload_info = *offloadInfo;
897 }
898 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;
909 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) {
924 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
925 }
926 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
927 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
928 }
929 // only allow deep buffering for music stream type
930 if (stream != AUDIO_STREAM_MUSIC) {
931 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
932 } else if (/* stream == AUDIO_STREAM_MUSIC && */
933 flags == AUDIO_OUTPUT_FLAG_NONE &&
934 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
935 // use DEEP_BUFFER as default output for music stream type
936 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
937 }
938 if (stream == AUDIO_STREAM_TTS) {
939 flags = AUDIO_OUTPUT_FLAG_TTS;
940 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
941 audio_is_linear_pcm(format)) {
942 flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
943 AUDIO_OUTPUT_FLAG_DIRECT);
944 ALOGV("Set VoIP and Direct output flags for PCM format");
945 }
946
947 sp<IOProfile> profile;
948
949 // skip direct output selection if the request can obviously be attached to a mixed output
950 // and not explicitly requested
951 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
952 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
953 audio_channel_count_from_out_mask(channelMask) <= 2) {
954 goto non_direct_output;
955 }
956
957 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
958 // This prevents creating an offloaded track and tearing it down immediately after start
959 // when audioflinger detects there is an active non offloadable effect.
960 // FIXME: We should check the audio session here but we do not have it in this context.
961 // This may prevent offloading in rare situations where effects are left active by apps
962 // in the background.
963
964 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
965 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
966 profile = getProfileForDirectOutput(device,
967 samplingRate,
968 format,
969 channelMask,
970 (audio_output_flags_t)flags);
971 }
972
973 if (profile != 0) {
974 sp<SwAudioOutputDescriptor> outputDesc = NULL;
975
976 for (size_t i = 0; i < mOutputs.size(); i++) {
977 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
978 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
979 outputDesc = desc;
980 // reuse direct output if currently open by the same client
981 // and configured with same parameters
982 if ((samplingRate == outputDesc->mSamplingRate) &&
983 audio_formats_match(format, outputDesc->mFormat) &&
984 (channelMask == outputDesc->mChannelMask)) {
985 if (session == outputDesc->mDirectClientSession) {
986 outputDesc->mDirectOpenCount++;
987 ALOGV("getOutput() reusing direct output %d for session %d",
988 mOutputs.keyAt(i), session);
989 return mOutputs.keyAt(i);
990 } else {
991 ALOGV("getOutput() do not reuse direct output because current client (%d) "
992 "is not the same as requesting client (%d)",
993 outputDesc->mDirectClientSession, session);
994 goto non_direct_output;
995 }
996 }
997 }
998 }
999 // close direct output if currently open and configured with different parameters
1000 if (outputDesc != NULL) {
1001 closeOutput(outputDesc->mIoHandle);
1002 }
1003
1004 // if the selected profile is offloaded and no offload info was specified,
1005 // create a default one
1006 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
1007 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
1008 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1009 defaultOffloadInfo.sample_rate = samplingRate;
1010 defaultOffloadInfo.channel_mask = channelMask;
1011 defaultOffloadInfo.format = format;
1012 defaultOffloadInfo.stream_type = stream;
1013 defaultOffloadInfo.bit_rate = 0;
1014 defaultOffloadInfo.duration_us = -1;
1015 defaultOffloadInfo.has_video = true; // conservative
1016 defaultOffloadInfo.is_streaming = true; // likely
1017 offloadInfo = &defaultOffloadInfo;
1018 }
1019
1020 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
1021 outputDesc->mDevice = device;
1022 outputDesc->mLatency = 0;
1023 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
1024 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1025 config.sample_rate = samplingRate;
1026 config.channel_mask = channelMask;
1027 config.format = format;
1028 if (offloadInfo != NULL) {
1029 config.offload_info = *offloadInfo;
1030 }
1031 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
1032 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
1033 : String8("");
1034 status = mpClientInterface->openOutput(profile->getModuleHandle(),
1035 &output,
1036 &config,
1037 &outputDesc->mDevice,
1038 address,
1039 &outputDesc->mLatency,
1040 outputDesc->mFlags);
1041
1042 // only accept an output with the requested parameters
1043 if (status != NO_ERROR ||
1044 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1045 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
1046 (channelMask != 0 && channelMask != config.channel_mask)) {
1047 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1048 "format %d %d, channelMask %04x %04x", output, samplingRate,
1049 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1050 outputDesc->mChannelMask);
1051 if (output != AUDIO_IO_HANDLE_NONE) {
1052 mpClientInterface->closeOutput(output);
1053 }
1054 // fall back to mixer output if possible when the direct output could not be open
1055 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
1056 goto non_direct_output;
1057 }
1058 return AUDIO_IO_HANDLE_NONE;
1059 }
1060 outputDesc->mSamplingRate = config.sample_rate;
1061 outputDesc->mChannelMask = config.channel_mask;
1062 outputDesc->mFormat = config.format;
1063 outputDesc->mRefCount[stream] = 0;
1064 outputDesc->mStopTime[stream] = 0;
1065 outputDesc->mDirectOpenCount = 1;
1066 outputDesc->mDirectClientSession = session;
1067
1068 addOutput(output, outputDesc);
1069 mPreviousOutputs = mOutputs;
1070 ALOGV("getOutput() returns new direct output %d", output);
1071 mpClientInterface->onAudioPortListUpdate();
1072 return output;
1073 }
1074
1075 non_direct_output:
1076
1077 // A request for HW A/V sync cannot fallback to a mixed output because time
1078 // stamps are embedded in audio data
1079 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1080 return AUDIO_IO_HANDLE_NONE;
1081 }
1082
1083 // ignoring channel mask due to downmix capability in mixer
1084
1085 // open a non direct output
1086
1087 // for non direct outputs, only PCM is supported
1088 if (audio_is_linear_pcm(format)) {
1089 // get which output is suitable for the specified stream. The actual
1090 // routing change will happen when startOutput() will be called
1091 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1092
1093 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1094 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1095 output = selectOutput(outputs, flags, format);
1096 }
1097 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1098 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1099
1100 return output;
1101 }
1102
selectOutput(const SortedVector<audio_io_handle_t> & outputs,audio_output_flags_t flags,audio_format_t format)1103 audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
1104 audio_output_flags_t flags,
1105 audio_format_t format)
1106 {
1107 // select one output among several that provide a path to a particular device or set of
1108 // devices (the list was previously build by getOutputsForDevice()).
1109 // The priority is as follows:
1110 // 1: the output with the highest number of requested policy flags
1111 // 2: the output with the bit depth the closest to the requested one
1112 // 3: the primary output
1113 // 4: the first output in the list
1114
1115 if (outputs.size() == 0) {
1116 return 0;
1117 }
1118 if (outputs.size() == 1) {
1119 return outputs[0];
1120 }
1121
1122 int maxCommonFlags = 0;
1123 audio_io_handle_t outputForFlags = 0;
1124 audio_io_handle_t outputForPrimary = 0;
1125 audio_io_handle_t outputForFormat = 0;
1126 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1127 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
1128
1129 for (size_t i = 0; i < outputs.size(); i++) {
1130 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
1131 if (!outputDesc->isDuplicated()) {
1132 // if a valid format is specified, skip output if not compatible
1133 if (format != AUDIO_FORMAT_INVALID) {
1134 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1135 if (!audio_formats_match(format, outputDesc->mFormat)) {
1136 continue;
1137 }
1138 } else if (!audio_is_linear_pcm(format)) {
1139 continue;
1140 }
1141 if (AudioPort::isBetterFormatMatch(
1142 outputDesc->mFormat, bestFormat, format)) {
1143 outputForFormat = outputs[i];
1144 bestFormat = outputDesc->mFormat;
1145 }
1146 }
1147
1148 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
1149 if (commonFlags >= maxCommonFlags) {
1150 if (commonFlags == maxCommonFlags) {
1151 if (AudioPort::isBetterFormatMatch(
1152 outputDesc->mFormat, bestFormatForFlags, format)) {
1153 outputForFlags = outputs[i];
1154 bestFormatForFlags = outputDesc->mFormat;
1155 }
1156 } else {
1157 outputForFlags = outputs[i];
1158 maxCommonFlags = commonFlags;
1159 bestFormatForFlags = outputDesc->mFormat;
1160 }
1161 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1162 }
1163 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
1164 outputForPrimary = outputs[i];
1165 }
1166 }
1167 }
1168
1169 if (outputForFlags != 0) {
1170 return outputForFlags;
1171 }
1172 if (outputForFormat != 0) {
1173 return outputForFormat;
1174 }
1175 if (outputForPrimary != 0) {
1176 return outputForPrimary;
1177 }
1178
1179 return outputs[0];
1180 }
1181
startOutput(audio_io_handle_t output,audio_stream_type_t stream,audio_session_t session)1182 status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
1183 audio_stream_type_t stream,
1184 audio_session_t session)
1185 {
1186 ALOGV("startOutput() output %d, stream %d, session %d",
1187 output, stream, session);
1188 ssize_t index = mOutputs.indexOfKey(output);
1189 if (index < 0) {
1190 ALOGW("startOutput() unknown output %d", output);
1191 return BAD_VALUE;
1192 }
1193
1194 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1195
1196 // Routing?
1197 mOutputRoutes.incRouteActivity(session);
1198
1199 audio_devices_t newDevice;
1200 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
1201 const char *address = NULL;
1202 if (policyMix != NULL) {
1203 address = policyMix->mDeviceAddress.string();
1204 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1205 newDevice = policyMix->mDeviceType;
1206 } else {
1207 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1208 }
1209 } else if (mOutputRoutes.hasRouteChanged(session)) {
1210 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
1211 checkStrategyRoute(getStrategy(stream), output);
1212 } else {
1213 newDevice = AUDIO_DEVICE_NONE;
1214 }
1215
1216 uint32_t delayMs = 0;
1217
1218 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
1219
1220 if (status != NO_ERROR) {
1221 mOutputRoutes.decRouteActivity(session);
1222 return status;
1223 }
1224 // Automatically enable the remote submix input when output is started on a re routing mix
1225 // of type MIX_TYPE_RECORDERS
1226 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1227 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1228 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1229 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1230 address,
1231 "remote-submix");
1232 }
1233
1234 if (delayMs != 0) {
1235 usleep(delayMs * 1000);
1236 }
1237
1238 return status;
1239 }
1240
startSource(const sp<AudioOutputDescriptor> & outputDesc,audio_stream_type_t stream,audio_devices_t device,const char * address,uint32_t * delayMs)1241 status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
1242 audio_stream_type_t stream,
1243 audio_devices_t device,
1244 const char *address,
1245 uint32_t *delayMs)
1246 {
1247 // cannot start playback of STREAM_TTS if any other output is being used
1248 uint32_t beaconMuteLatency = 0;
1249
1250 *delayMs = 0;
1251 if (stream == AUDIO_STREAM_TTS) {
1252 ALOGV("\t found BEACON stream");
1253 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1254 return INVALID_OPERATION;
1255 } else {
1256 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1257 }
1258 } else {
1259 // some playback other than beacon starts
1260 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1261 }
1262
1263 // force device change if the output is inactive and no audio patch is already present.
1264 // check active before incrementing usage count
1265 bool force = !outputDesc->isActive() &&
1266 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
1267
1268 // increment usage count for this stream on the requested output:
1269 // NOTE that the usage count is the same for duplicated output and hardware output which is
1270 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1271 outputDesc->changeRefCount(stream, 1);
1272
1273 if (stream == AUDIO_STREAM_MUSIC) {
1274 selectOutputForMusicEffects();
1275 }
1276
1277 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
1278 // starting an output being rerouted?
1279 if (device == AUDIO_DEVICE_NONE) {
1280 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1281 }
1282
1283 routing_strategy strategy = getStrategy(stream);
1284 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
1285 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1286 (beaconMuteLatency > 0);
1287 uint32_t waitMs = beaconMuteLatency;
1288 for (size_t i = 0; i < mOutputs.size(); i++) {
1289 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
1290 if (desc != outputDesc) {
1291 // force a device change if any other output is:
1292 // - managed by the same hw module
1293 // - has a current device selection that differs from selected device.
1294 // - supports currently selected device
1295 // - has an active audio patch
1296 // In this case, the audio HAL must receive the new device selection so that it can
1297 // change the device currently selected by the other active output.
1298 if (outputDesc->sharesHwModuleWith(desc) &&
1299 desc->device() != device &&
1300 desc->supportedDevices() & device &&
1301 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
1302 force = true;
1303 }
1304 // wait for audio on other active outputs to be presented when starting
1305 // a notification so that audio focus effect can propagate, or that a mute/unmute
1306 // event occurred for beacon
1307 uint32_t latency = desc->latency();
1308 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1309 waitMs = latency;
1310 }
1311 }
1312 }
1313 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
1314
1315 // handle special case for sonification while in call
1316 if (isInCall()) {
1317 handleIncallSonification(stream, true, false);
1318 }
1319
1320 // apply volume rules for current stream and device if necessary
1321 checkAndSetVolume(stream,
1322 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
1323 outputDesc,
1324 outputDesc->device());
1325
1326 // update the outputs if starting an output with a stream that can affect notification
1327 // routing
1328 handleNotificationRoutingForStream(stream);
1329
1330 // force reevaluating accessibility routing when ringtone or alarm starts
1331 if (strategy == STRATEGY_SONIFICATION) {
1332 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1333 }
1334
1335 if (waitMs > muteWaitMs) {
1336 *delayMs = waitMs - muteWaitMs;
1337 }
1338 }
1339
1340 return NO_ERROR;
1341 }
1342
1343
stopOutput(audio_io_handle_t output,audio_stream_type_t stream,audio_session_t session)1344 status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
1345 audio_stream_type_t stream,
1346 audio_session_t session)
1347 {
1348 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1349 ssize_t index = mOutputs.indexOfKey(output);
1350 if (index < 0) {
1351 ALOGW("stopOutput() unknown output %d", output);
1352 return BAD_VALUE;
1353 }
1354
1355 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1356
1357 if (outputDesc->mRefCount[stream] == 1) {
1358 // Automatically disable the remote submix input when output is stopped on a
1359 // re routing mix of type MIX_TYPE_RECORDERS
1360 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
1361 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1362 policyMix != NULL &&
1363 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1364 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1365 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1366 policyMix->mDeviceAddress,
1367 "remote-submix");
1368 }
1369 }
1370
1371 // Routing?
1372 bool forceDeviceUpdate = false;
1373 if (outputDesc->mRefCount[stream] > 0) {
1374 int activityCount = mOutputRoutes.decRouteActivity(session);
1375 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1376
1377 if (forceDeviceUpdate) {
1378 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1379 }
1380 }
1381
1382 return stopSource(outputDesc, stream, forceDeviceUpdate);
1383 }
1384
stopSource(const sp<AudioOutputDescriptor> & outputDesc,audio_stream_type_t stream,bool forceDeviceUpdate)1385 status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
1386 audio_stream_type_t stream,
1387 bool forceDeviceUpdate)
1388 {
1389 // always handle stream stop, check which stream type is stopping
1390 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1391
1392 // handle special case for sonification while in call
1393 if (isInCall()) {
1394 handleIncallSonification(stream, false, false);
1395 }
1396
1397 if (outputDesc->mRefCount[stream] > 0) {
1398 // decrement usage count of this stream on the output
1399 outputDesc->changeRefCount(stream, -1);
1400
1401 // store time at which the stream was stopped - see isStreamActive()
1402 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
1403 outputDesc->mStopTime[stream] = systemTime();
1404 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
1405 // delay the device switch by twice the latency because stopOutput() is executed when
1406 // the track stop() command is received and at that time the audio track buffer can
1407 // still contain data that needs to be drained. The latency only covers the audio HAL
1408 // and kernel buffers. Also the latency does not always include additional delay in the
1409 // audio path (audio DSP, CODEC ...)
1410 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
1411
1412 // force restoring the device selection on other active outputs if it differs from the
1413 // one being selected for this output
1414 uint32_t delayMs = outputDesc->latency()*2;
1415 for (size_t i = 0; i < mOutputs.size(); i++) {
1416 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
1417 if (desc != outputDesc &&
1418 desc->isActive() &&
1419 outputDesc->sharesHwModuleWith(desc) &&
1420 (newDevice != desc->device())) {
1421 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1422 bool force = desc->device() != newDevice2;
1423 setOutputDevice(desc,
1424 newDevice2,
1425 force,
1426 delayMs);
1427 // re-apply device specific volume if not done by setOutputDevice()
1428 if (!force) {
1429 applyStreamVolumes(desc, newDevice2, delayMs);
1430 }
1431 }
1432 }
1433 // update the outputs if stopping one with a stream that can affect notification routing
1434 handleNotificationRoutingForStream(stream);
1435 }
1436 if (stream == AUDIO_STREAM_MUSIC) {
1437 selectOutputForMusicEffects();
1438 }
1439 return NO_ERROR;
1440 } else {
1441 ALOGW("stopOutput() refcount is already 0");
1442 return INVALID_OPERATION;
1443 }
1444 }
1445
releaseOutput(audio_io_handle_t output,audio_stream_type_t stream __unused,audio_session_t session __unused)1446 void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
1447 audio_stream_type_t stream __unused,
1448 audio_session_t session __unused)
1449 {
1450 ALOGV("releaseOutput() %d", output);
1451 ssize_t index = mOutputs.indexOfKey(output);
1452 if (index < 0) {
1453 ALOGW("releaseOutput() releasing unknown output %d", output);
1454 return;
1455 }
1456
1457 #ifdef AUDIO_POLICY_TEST
1458 int testIndex = testOutputIndex(output);
1459 if (testIndex != 0) {
1460 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1461 if (outputDesc->isActive()) {
1462 mpClientInterface->closeOutput(output);
1463 removeOutput(output);
1464 mTestOutputs[testIndex] = 0;
1465 }
1466 return;
1467 }
1468 #endif //AUDIO_POLICY_TEST
1469
1470 // Routing
1471 mOutputRoutes.removeRoute(session);
1472
1473 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
1474 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1475 if (desc->mDirectOpenCount <= 0) {
1476 ALOGW("releaseOutput() invalid open count %d for output %d",
1477 desc->mDirectOpenCount, output);
1478 return;
1479 }
1480 if (--desc->mDirectOpenCount == 0) {
1481 closeOutput(output);
1482 mpClientInterface->onAudioPortListUpdate();
1483 }
1484 }
1485 }
1486
1487
getInputForAttr(const audio_attributes_t * attr,audio_io_handle_t * input,audio_session_t session,uid_t uid,const audio_config_base_t * config,audio_input_flags_t flags,audio_port_handle_t * selectedDeviceId,input_type_t * inputType,audio_port_handle_t * portId)1488 status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1489 audio_io_handle_t *input,
1490 audio_session_t session,
1491 uid_t uid,
1492 const audio_config_base_t *config,
1493 audio_input_flags_t flags,
1494 audio_port_handle_t *selectedDeviceId,
1495 input_type_t *inputType,
1496 audio_port_handle_t *portId)
1497 {
1498 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1499 "session %d, flags %#x",
1500 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
1501
1502 status_t status = NO_ERROR;
1503 // handle legacy remote submix case where the address was not always specified
1504 String8 address = String8("");
1505 audio_source_t halInputSource;
1506 audio_source_t inputSource = attr->source;
1507 sp<AudioPolicyMix> policyMix;
1508 DeviceVector inputDevices;
1509
1510 // Explicit routing?
1511 sp<DeviceDescriptor> deviceDesc;
1512 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
1513 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1514 if (mAvailableInputDevices[i]->getId() == *selectedDeviceId) {
1515 deviceDesc = mAvailableInputDevices[i];
1516 break;
1517 }
1518 }
1519 }
1520 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
1521
1522 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1523 // possible
1524 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1525 *input != AUDIO_IO_HANDLE_NONE) {
1526 ssize_t index = mInputs.indexOfKey(*input);
1527 if (index < 0) {
1528 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1529 status = BAD_VALUE;
1530 goto error;
1531 }
1532 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1533 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1534 if (audioSession == 0) {
1535 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1536 status = BAD_VALUE;
1537 goto error;
1538 }
1539 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1540 // The second call is for the first active client and sets the UID. Any further call
1541 // corresponds to a new client and is only permitted from the same UId.
1542 if (audioSession->openCount() == 1) {
1543 audioSession->setUid(uid);
1544 } else if (audioSession->uid() != uid) {
1545 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1546 uid, session, audioSession->uid());
1547 status = INVALID_OPERATION;
1548 goto error;
1549 }
1550 audioSession->changeOpenCount(1);
1551 *inputType = API_INPUT_LEGACY;
1552 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1553 *portId = AudioPort::getNextUniqueId();
1554 }
1555 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1556 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1557 : AUDIO_PORT_HANDLE_NONE;
1558 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1559
1560 return NO_ERROR;
1561 }
1562
1563 *input = AUDIO_IO_HANDLE_NONE;
1564 *inputType = API_INPUT_INVALID;
1565
1566 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1567 inputSource = AUDIO_SOURCE_MIC;
1568 }
1569 halInputSource = inputSource;
1570
1571 // TODO: check for existing client for this port ID
1572 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1573 *portId = AudioPort::getNextUniqueId();
1574 }
1575
1576 audio_devices_t device;
1577
1578 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
1579 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
1580 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1581 if (status != NO_ERROR) {
1582 goto error;
1583 }
1584 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1585 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1586 address = String8(attr->tags + strlen("addr="));
1587 } else {
1588 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1589 if (device == AUDIO_DEVICE_NONE) {
1590 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
1591 status = BAD_VALUE;
1592 goto error;
1593 }
1594 if (policyMix != NULL) {
1595 address = policyMix->mDeviceAddress;
1596 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1597 // there is an external policy, but this input is attached to a mix of recorders,
1598 // meaning it receives audio injected into the framework, so the recorder doesn't
1599 // know about it and is therefore considered "legacy"
1600 *inputType = API_INPUT_LEGACY;
1601 } else {
1602 // recording a mix of players defined by an external policy, we're rerouting for
1603 // an external policy
1604 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1605 }
1606 } else if (audio_is_remote_submix_device(device)) {
1607 address = String8("0");
1608 *inputType = API_INPUT_MIX_CAPTURE;
1609 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1610 *inputType = API_INPUT_TELEPHONY_RX;
1611 } else {
1612 *inputType = API_INPUT_LEGACY;
1613 }
1614
1615 }
1616
1617 *input = getInputForDevice(device, address, session, uid, inputSource,
1618 config->sample_rate, config->format, config->channel_mask, flags,
1619 policyMix);
1620 if (*input == AUDIO_IO_HANDLE_NONE) {
1621 status = INVALID_OPERATION;
1622 goto error;
1623 }
1624
1625 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1626 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1627 : AUDIO_PORT_HANDLE_NONE;
1628
1629 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1630 *input, *inputType, *selectedDeviceId);
1631
1632 return NO_ERROR;
1633
1634 error:
1635 mInputRoutes.removeRoute(session);
1636 return status;
1637 }
1638
1639
getInputForDevice(audio_devices_t device,String8 address,audio_session_t session,uid_t uid,audio_source_t inputSource,uint32_t samplingRate,audio_format_t format,audio_channel_mask_t channelMask,audio_input_flags_t flags,const sp<AudioPolicyMix> & policyMix)1640 audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1641 String8 address,
1642 audio_session_t session,
1643 uid_t uid,
1644 audio_source_t inputSource,
1645 uint32_t samplingRate,
1646 audio_format_t format,
1647 audio_channel_mask_t channelMask,
1648 audio_input_flags_t flags,
1649 const sp<AudioPolicyMix> &policyMix)
1650 {
1651 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1652 audio_source_t halInputSource = inputSource;
1653 bool isSoundTrigger = false;
1654
1655 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1656 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1657 if (index >= 0) {
1658 input = mSoundTriggerSessions.valueFor(session);
1659 isSoundTrigger = true;
1660 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1661 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1662 } else {
1663 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1664 }
1665 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
1666 audio_is_linear_pcm(format)) {
1667 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
1668 }
1669
1670 // find a compatible input profile (not necessarily identical in parameters)
1671 sp<IOProfile> profile;
1672 // samplingRate and flags may be updated by getInputProfile
1673 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
1674 audio_format_t profileFormat = format;
1675 audio_channel_mask_t profileChannelMask = channelMask;
1676 audio_input_flags_t profileFlags = flags;
1677 for (;;) {
1678 profile = getInputProfile(device, address,
1679 profileSamplingRate, profileFormat, profileChannelMask,
1680 profileFlags);
1681 if (profile != 0) {
1682 break; // success
1683 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1684 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
1685 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1686 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1687 } else { // fail
1688 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1689 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
1690 device, samplingRate, format, channelMask, flags);
1691 return input;
1692 }
1693 }
1694 // Pick input sampling rate if not specified by client
1695 if (samplingRate == 0) {
1696 samplingRate = profileSamplingRate;
1697 }
1698
1699 if (profile->getModuleHandle() == 0) {
1700 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
1701 return input;
1702 }
1703
1704 sp<AudioSession> audioSession = new AudioSession(session,
1705 inputSource,
1706 format,
1707 samplingRate,
1708 channelMask,
1709 flags,
1710 uid,
1711 isSoundTrigger,
1712 policyMix, mpClientInterface);
1713
1714 // FIXME: disable concurrent capture until UI is ready
1715 #if 0
1716 // reuse an open input if possible
1717 sp<AudioInputDescriptor> reusedInputDesc;
1718 for (size_t i = 0; i < mInputs.size(); i++) {
1719 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
1720 // reuse input if:
1721 // - it shares the same profile
1722 // AND
1723 // - it is not a reroute submix input
1724 // AND
1725 // - it is: not used for sound trigger
1726 // OR
1727 // used for sound trigger and all clients use the same session ID
1728 //
1729 if ((profile == desc->mProfile) &&
1730 (isSoundTrigger == desc->isSoundTrigger()) &&
1731 !is_virtual_input_device(device)) {
1732
1733 sp<AudioSession> as = desc->getAudioSession(session);
1734 if (as != 0) {
1735 // do not allow unmatching properties on same session
1736 if (as->matches(audioSession)) {
1737 as->changeOpenCount(1);
1738 } else {
1739 ALOGW("getInputForDevice() record with different attributes"
1740 " exists for session %d", session);
1741 continue;
1742 }
1743 } else if (isSoundTrigger) {
1744 continue;
1745 }
1746
1747 // Reuse the already opened input stream on this profile if:
1748 // - the new capture source is background OR
1749 // - the path requested configurations match OR
1750 // - the new source priority is less than the highest source priority on this input
1751 // If the input stream cannot be reused, close it before opening a new stream
1752 // on the same profile for the new client so that the requested path configuration
1753 // can be selected.
1754 if (!isConcurrentSource(inputSource) &&
1755 ((desc->mSamplingRate != samplingRate ||
1756 desc->mChannelMask != channelMask ||
1757 !audio_formats_match(desc->mFormat, format)) &&
1758 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
1759 source_priority(inputSource)))) {
1760 reusedInputDesc = desc;
1761 continue;
1762 } else {
1763 desc->addAudioSession(session, audioSession);
1764 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1765 return mInputs.keyAt(i);
1766 }
1767 }
1768 }
1769
1770 if (reusedInputDesc != 0) {
1771 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1772 for (size_t j = 0; j < sessions.size(); j++) {
1773 audio_session_t currentSession = sessions.keyAt(j);
1774 stopInput(reusedInputDesc->mIoHandle, currentSession);
1775 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1776 }
1777 }
1778 #endif
1779
1780 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1781 config.sample_rate = profileSamplingRate;
1782 config.channel_mask = profileChannelMask;
1783 config.format = profileFormat;
1784
1785 if (address == "") {
1786 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1787 // the inputs vector must be of size 1, but we don't want to crash here
1788 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1789 }
1790
1791 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
1792 &input,
1793 &config,
1794 &device,
1795 address,
1796 halInputSource,
1797 profileFlags);
1798
1799 // only accept input with the exact requested set of parameters
1800 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
1801 (profileSamplingRate != config.sample_rate) ||
1802 !audio_formats_match(profileFormat, config.format) ||
1803 (profileChannelMask != config.channel_mask)) {
1804 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1805 ", format %d, channelMask %x",
1806 samplingRate, format, channelMask);
1807 if (input != AUDIO_IO_HANDLE_NONE) {
1808 mpClientInterface->closeInput(input);
1809 }
1810 return AUDIO_IO_HANDLE_NONE;
1811 }
1812
1813 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
1814 inputDesc->mSamplingRate = profileSamplingRate;
1815 inputDesc->mFormat = profileFormat;
1816 inputDesc->mChannelMask = profileChannelMask;
1817 inputDesc->mDevice = device;
1818 inputDesc->mPolicyMix = policyMix;
1819 inputDesc->addAudioSession(session, audioSession);
1820
1821 addInput(input, inputDesc);
1822 mpClientInterface->onAudioPortListUpdate();
1823
1824 return input;
1825 }
1826
1827 //static
isConcurrentSource(audio_source_t source)1828 bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1829 {
1830 return (source == AUDIO_SOURCE_HOTWORD) ||
1831 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1832 (source == AUDIO_SOURCE_FM_TUNER);
1833 }
1834
isConcurentCaptureAllowed(const sp<AudioInputDescriptor> & inputDesc,const sp<AudioSession> & audioSession)1835 bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1836 const sp<AudioSession>& audioSession)
1837 {
1838 // Do not allow capture if an active voice call is using a software patch and
1839 // the call TX source device is on the same HW module.
1840 // FIXME: would be better to refine to only inputs whose profile connects to the
1841 // call TX device but this information is not in the audio patch
1842 if (mCallTxPatch != 0 &&
1843 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1844 return false;
1845 }
1846
1847 // starting concurrent capture is enabled if:
1848 // 1) capturing for re-routing
1849 // 2) capturing for HOTWORD source
1850 // 3) capturing for FM TUNER source
1851 // 3) All other active captures are either for re-routing or HOTWORD
1852
1853 if (is_virtual_input_device(inputDesc->mDevice) ||
1854 isConcurrentSource(audioSession->inputSource())) {
1855 return true;
1856 }
1857
1858 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1859 for (size_t i = 0; i < activeInputs.size(); i++) {
1860 sp<AudioInputDescriptor> activeInput = activeInputs[i];
1861 if (!isConcurrentSource(activeInput->inputSource(true)) &&
1862 !is_virtual_input_device(activeInput->mDevice)) {
1863 return false;
1864 }
1865 }
1866
1867 return true;
1868 }
1869
1870 // FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
soundTriggerSupportsConcurrentCapture()1871 bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1872 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1873 bool soundTriggerSupportsConcurrentCapture = false;
1874 unsigned int numModules = 0;
1875 struct sound_trigger_module_descriptor* nModules = NULL;
1876
1877 status_t status = SoundTrigger::listModules(nModules, &numModules);
1878 if (status == NO_ERROR && numModules != 0) {
1879 nModules = (struct sound_trigger_module_descriptor*) calloc(
1880 numModules, sizeof(struct sound_trigger_module_descriptor));
1881 if (nModules == NULL) {
1882 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1883 // ram the next time this function is called.
1884 ALOGE("Failed to allocate buffer for module descriptors");
1885 return false;
1886 }
1887
1888 status = SoundTrigger::listModules(nModules, &numModules);
1889 if (status == NO_ERROR) {
1890 soundTriggerSupportsConcurrentCapture = true;
1891 for (size_t i = 0; i < numModules; ++i) {
1892 soundTriggerSupportsConcurrentCapture &=
1893 nModules[i].properties.concurrent_capture;
1894 }
1895 }
1896 free(nModules);
1897 }
1898 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1899 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1900 }
1901 return mSoundTriggerSupportsConcurrentCapture;
1902 }
1903
1904
startInput(audio_io_handle_t input,audio_session_t session,concurrency_type__mask_t * concurrency)1905 status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1906 audio_session_t session,
1907 concurrency_type__mask_t *concurrency)
1908 {
1909 ALOGV("startInput() input %d", input);
1910 *concurrency = API_INPUT_CONCURRENCY_NONE;
1911 ssize_t index = mInputs.indexOfKey(input);
1912 if (index < 0) {
1913 ALOGW("startInput() unknown input %d", input);
1914 return BAD_VALUE;
1915 }
1916 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1917
1918 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1919 if (audioSession == 0) {
1920 ALOGW("startInput() unknown session %d on input %d", session, input);
1921 return BAD_VALUE;
1922 }
1923
1924 // FIXME: disable concurrent capture until UI is ready
1925 #if 0
1926 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1927 ALOGW("startInput(%d) failed: other input already started", input);
1928 return INVALID_OPERATION;
1929 }
1930
1931 if (isInCall()) {
1932 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1933 }
1934 if (mInputs.activeInputsCountOnDevices() != 0) {
1935 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
1936 }
1937 #else
1938 if (!is_virtual_input_device(inputDesc->mDevice)) {
1939 if (mCallTxPatch != 0 &&
1940 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1941 ALOGW("startInput(%d) failed: call in progress", input);
1942 return INVALID_OPERATION;
1943 }
1944
1945 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1946 for (size_t i = 0; i < activeInputs.size(); i++) {
1947 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1948
1949 if (is_virtual_input_device(activeDesc->mDevice)) {
1950 continue;
1951 }
1952
1953 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1954 activeDesc->getId() == inputDesc->getId()) {
1955 continue;
1956 }
1957
1958 audio_source_t activeSource = activeDesc->inputSource(true);
1959 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1960 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1961 if (activeDesc->hasPreemptedSession(session)) {
1962 ALOGW("startInput(%d) failed for HOTWORD: "
1963 "other input %d already started for HOTWORD",
1964 input, activeDesc->mIoHandle);
1965 return INVALID_OPERATION;
1966 }
1967 } else {
1968 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1969 input, activeDesc->mIoHandle);
1970 return INVALID_OPERATION;
1971 }
1972 } else {
1973 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1974 ALOGW("startInput(%d) failed: other input %d already started",
1975 input, activeDesc->mIoHandle);
1976 return INVALID_OPERATION;
1977 }
1978 }
1979 }
1980
1981 // We only need to check if the sound trigger session supports concurrent capture if the
1982 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1983 // that's running.
1984 const bool allowConcurrentWithSoundTrigger =
1985 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1986
1987 // if capture is allowed, preempt currently active HOTWORD captures
1988 for (size_t i = 0; i < activeInputs.size(); i++) {
1989 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1990
1991 if (is_virtual_input_device(activeDesc->mDevice)) {
1992 continue;
1993 }
1994
1995 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1996 continue;
1997 }
1998
1999 audio_source_t activeSource = activeDesc->inputSource(true);
2000 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2001 AudioSessionCollection activeSessions =
2002 activeDesc->getAudioSessions(true /*activeOnly*/);
2003 audio_session_t activeSession = activeSessions.keyAt(0);
2004 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
2005 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
2006 sessions.add(activeSession);
2007 inputDesc->setPreemptedSessions(sessions);
2008 stopInput(activeHandle, activeSession);
2009 releaseInput(activeHandle, activeSession);
2010 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2011 input, activeDesc->mIoHandle);
2012 }
2013 }
2014 }
2015 #endif
2016
2017 // increment activity count before calling getNewInputDevice() below as only active sessions
2018 // are considered for device selection
2019 audioSession->changeActiveCount(1);
2020
2021 // Routing?
2022 mInputRoutes.incRouteActivity(session);
2023
2024 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
2025 // indicate active capture to sound trigger service if starting capture from a mic on
2026 // primary HW module
2027 audio_devices_t device = getNewInputDevice(inputDesc);
2028 setInputDevice(input, device, true /* force */);
2029
2030 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
2031 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
2032 // if input maps to a dynamic policy with an activity listener, notify of state change
2033 if ((policyMix != NULL)
2034 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2035 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
2036 MIX_STATE_MIXING);
2037 }
2038
2039 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2040 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2041 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2042 SoundTrigger::setCaptureState(true);
2043 }
2044
2045 // automatically enable the remote submix output when input is started if not
2046 // used by a policy mix of type MIX_TYPE_RECORDERS
2047 // For remote submix (a virtual device), we open only one input per capture request.
2048 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2049 String8 address = String8("");
2050 if (policyMix == NULL) {
2051 address = String8("0");
2052 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2053 address = policyMix->mDeviceAddress;
2054 }
2055 if (address != "") {
2056 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2057 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2058 address, "remote-submix");
2059 }
2060 }
2061 }
2062 }
2063
2064 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
2065
2066 return NO_ERROR;
2067 }
2068
stopInput(audio_io_handle_t input,audio_session_t session)2069 status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2070 audio_session_t session)
2071 {
2072 ALOGV("stopInput() input %d", input);
2073 ssize_t index = mInputs.indexOfKey(input);
2074 if (index < 0) {
2075 ALOGW("stopInput() unknown input %d", input);
2076 return BAD_VALUE;
2077 }
2078 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2079
2080 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
2081 if (index < 0) {
2082 ALOGW("stopInput() unknown session %d on input %d", session, input);
2083 return BAD_VALUE;
2084 }
2085
2086 if (audioSession->activeCount() == 0) {
2087 ALOGW("stopInput() input %d already stopped", input);
2088 return INVALID_OPERATION;
2089 }
2090
2091 audioSession->changeActiveCount(-1);
2092
2093 // Routing?
2094 mInputRoutes.decRouteActivity(session);
2095
2096 if (audioSession->activeCount() == 0) {
2097
2098 if (inputDesc->isActive()) {
2099 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2100 } else {
2101 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
2102 // if input maps to a dynamic policy with an activity listener, notify of state change
2103 if ((policyMix != NULL)
2104 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2105 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
2106 MIX_STATE_IDLE);
2107 }
2108
2109 // automatically disable the remote submix output when input is stopped if not
2110 // used by a policy mix of type MIX_TYPE_RECORDERS
2111 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2112 String8 address = String8("");
2113 if (policyMix == NULL) {
2114 address = String8("0");
2115 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2116 address = policyMix->mDeviceAddress;
2117 }
2118 if (address != "") {
2119 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2120 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2121 address, "remote-submix");
2122 }
2123 }
2124
2125 audio_devices_t device = inputDesc->mDevice;
2126 resetInputDevice(input);
2127
2128 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2129 // primary HW module
2130 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2131 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2132 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2133 SoundTrigger::setCaptureState(false);
2134 }
2135 inputDesc->clearPreemptedSessions();
2136 }
2137 }
2138 return NO_ERROR;
2139 }
2140
releaseInput(audio_io_handle_t input,audio_session_t session)2141 void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2142 audio_session_t session)
2143 {
2144
2145 ALOGV("releaseInput() %d", input);
2146 ssize_t index = mInputs.indexOfKey(input);
2147 if (index < 0) {
2148 ALOGW("releaseInput() releasing unknown input %d", input);
2149 return;
2150 }
2151
2152 // Routing
2153 mInputRoutes.removeRoute(session);
2154
2155 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2156 ALOG_ASSERT(inputDesc != 0);
2157
2158 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
2159 if (audioSession == 0) {
2160 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2161 return;
2162 }
2163
2164 if (audioSession->openCount() == 0) {
2165 ALOGW("releaseInput() invalid open count %d on session %d",
2166 audioSession->openCount(), session);
2167 return;
2168 }
2169
2170 if (audioSession->changeOpenCount(-1) == 0) {
2171 inputDesc->removeAudioSession(session);
2172 }
2173
2174 if (inputDesc->getOpenRefCount() > 0) {
2175 ALOGV("releaseInput() exit > 0");
2176 return;
2177 }
2178
2179 closeInput(input);
2180 mpClientInterface->onAudioPortListUpdate();
2181 ALOGV("releaseInput() exit");
2182 }
2183
closeAllInputs()2184 void AudioPolicyManager::closeAllInputs() {
2185 bool patchRemoved = false;
2186
2187 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2188 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
2189 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
2190 if (patch_index >= 0) {
2191 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
2192 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2193 mAudioPatches.removeItemsAt(patch_index);
2194 patchRemoved = true;
2195 }
2196 mpClientInterface->closeInput(mInputs.keyAt(input_index));
2197 }
2198 mInputs.clear();
2199 SoundTrigger::setCaptureState(false);
2200 nextAudioPortGeneration();
2201
2202 if (patchRemoved) {
2203 mpClientInterface->onAudioPatchListUpdate();
2204 }
2205 }
2206
initStreamVolume(audio_stream_type_t stream,int indexMin,int indexMax)2207 void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
2208 int indexMin,
2209 int indexMax)
2210 {
2211 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
2212 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
2213
2214 // initialize other private stream volumes which follow this one
2215 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2216 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
2217 continue;
2218 }
2219 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
2220 }
2221 }
2222
setStreamVolumeIndex(audio_stream_type_t stream,int index,audio_devices_t device)2223 status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
2224 int index,
2225 audio_devices_t device)
2226 {
2227
2228 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
2229 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
2230 return BAD_VALUE;
2231 }
2232 if (!audio_is_output_device(device)) {
2233 return BAD_VALUE;
2234 }
2235
2236 // Force max volume if stream cannot be muted
2237 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
2238
2239 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
2240 stream, device, index);
2241
2242 // update other private stream volumes which follow this one
2243 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2244 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
2245 continue;
2246 }
2247 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2248 }
2249
2250 // update volume on all outputs and streams matching the following:
2251 // - The requested stream (or a stream matching for volume control) is active on the output
2252 // - The device (or devices) selected by the strategy corresponding to this stream includes
2253 // the requested device
2254 // - For non default requested device, currently selected device on the output is either the
2255 // requested device or one of the devices selected by the strategy
2256 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2257 // no specific device volume value exists for currently selected device.
2258 status_t status = NO_ERROR;
2259 for (size_t i = 0; i < mOutputs.size(); i++) {
2260 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2261 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
2262 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2263 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
2264 continue;
2265 }
2266 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2267 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
2268 continue;
2269 }
2270 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
2271 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2272 curStrategy, false /*fromCache*/));
2273 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2274 ((curStreamDevice & device) == 0)) {
2275 continue;
2276 }
2277 bool applyVolume;
2278 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2279 curStreamDevice |= device;
2280 applyVolume = (curDevice & curStreamDevice) != 0;
2281 } else {
2282 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
2283 stream, curStreamDevice);
2284 }
2285
2286 if (applyVolume) {
2287 //FIXME: workaround for truncated touch sounds
2288 // delayed volume change for system stream to be removed when the problem is
2289 // handled by system UI
2290 status_t volStatus =
2291 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2292 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
2293 if (volStatus != NO_ERROR) {
2294 status = volStatus;
2295 }
2296 }
2297 }
2298 }
2299 return status;
2300 }
2301
getStreamVolumeIndex(audio_stream_type_t stream,int * index,audio_devices_t device)2302 status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
2303 int *index,
2304 audio_devices_t device)
2305 {
2306 if (index == NULL) {
2307 return BAD_VALUE;
2308 }
2309 if (!audio_is_output_device(device)) {
2310 return BAD_VALUE;
2311 }
2312 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
2313 // the strategy the stream belongs to.
2314 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2315 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2316 }
2317 device = Volume::getDeviceForVolume(device);
2318
2319 *index = mVolumeCurves->getVolumeIndex(stream, device);
2320 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2321 return NO_ERROR;
2322 }
2323
selectOutputForMusicEffects()2324 audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
2325 {
2326 // select one output among several suitable for global effects.
2327 // The priority is as follows:
2328 // 1: An offloaded output. If the effect ends up not being offloadable,
2329 // AudioFlinger will invalidate the track and the offloaded output
2330 // will be closed causing the effect to be moved to a PCM output.
2331 // 2: A deep buffer output
2332 // 3: The primary output
2333 // 4: the first output in the list
2334
2335 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
2336 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2337 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2338
2339 if (outputs.size() == 0) {
2340 return AUDIO_IO_HANDLE_NONE;
2341 }
2342
2343 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2344 bool activeOnly = true;
2345
2346 while (output == AUDIO_IO_HANDLE_NONE) {
2347 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2348 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2349 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2350
2351 for (size_t i = 0; i < outputs.size(); i++) {
2352 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
2353 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2354 continue;
2355 }
2356 ALOGV("selectOutputForMusicEffects activeOnly %d outputs[%zu] flags 0x%08x",
2357 activeOnly, i, desc->mFlags);
2358 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2359 outputOffloaded = outputs[i];
2360 }
2361 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2362 outputDeepBuffer = outputs[i];
2363 }
2364 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
2365 outputPrimary = outputs[i];
2366 }
2367 }
2368 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2369 output = outputOffloaded;
2370 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2371 output = outputDeepBuffer;
2372 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2373 output = outputPrimary;
2374 } else {
2375 output = outputs[0];
2376 }
2377 activeOnly = false;
2378 }
2379
2380 if (output != mMusicEffectOutput) {
2381 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2382 mMusicEffectOutput = output;
2383 }
2384
2385 ALOGV("selectOutputForMusicEffects selected output %d", output);
2386 return output;
2387 }
2388
getOutputForEffect(const effect_descriptor_t * desc __unused)2389 audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2390 {
2391 return selectOutputForMusicEffects();
2392 }
2393
registerEffect(const effect_descriptor_t * desc,audio_io_handle_t io,uint32_t strategy,int session,int id)2394 status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
2395 audio_io_handle_t io,
2396 uint32_t strategy,
2397 int session,
2398 int id)
2399 {
2400 ssize_t index = mOutputs.indexOfKey(io);
2401 if (index < 0) {
2402 index = mInputs.indexOfKey(io);
2403 if (index < 0) {
2404 ALOGW("registerEffect() unknown io %d", io);
2405 return INVALID_OPERATION;
2406 }
2407 }
2408 return mEffects.registerEffect(desc, io, strategy, session, id);
2409 }
2410
isStreamActive(audio_stream_type_t stream,uint32_t inPastMs) const2411 bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2412 {
2413 bool active = false;
2414 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2415 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
2416 continue;
2417 }
2418 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2419 }
2420 return active;
2421 }
2422
isStreamActiveRemotely(audio_stream_type_t stream,uint32_t inPastMs) const2423 bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2424 {
2425 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2426 }
2427
isSourceActive(audio_source_t source) const2428 bool AudioPolicyManager::isSourceActive(audio_source_t source) const
2429 {
2430 for (size_t i = 0; i < mInputs.size(); i++) {
2431 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
2432 if (inputDescriptor->isSourceActive(source)) {
2433 return true;
2434 }
2435 }
2436 return false;
2437 }
2438
2439 // Register a list of custom mixes with their attributes and format.
2440 // When a mix is registered, corresponding input and output profiles are
2441 // added to the remote submix hw module. The profile contains only the
2442 // parameters (sampling rate, format...) specified by the mix.
2443 // The corresponding input remote submix device is also connected.
2444 //
2445 // When a remote submix device is connected, the address is checked to select the
2446 // appropriate profile and the corresponding input or output stream is opened.
2447 //
2448 // When capture starts, getInputForAttr() will:
2449 // - 1 look for a mix matching the address passed in attribtutes tags if any
2450 // - 2 if none found, getDeviceForInputSource() will:
2451 // - 2.1 look for a mix matching the attributes source
2452 // - 2.2 if none found, default to device selection by policy rules
2453 // At this time, the corresponding output remote submix device is also connected
2454 // and active playback use cases can be transferred to this mix if needed when reconnecting
2455 // after AudioTracks are invalidated
2456 //
2457 // When playback starts, getOutputForAttr() will:
2458 // - 1 look for a mix matching the address passed in attribtutes tags if any
2459 // - 2 if none found, look for a mix matching the attributes usage
2460 // - 3 if none found, default to device and output selection by policy rules.
2461
registerPolicyMixes(const Vector<AudioMix> & mixes)2462 status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
2463 {
2464 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2465 status_t res = NO_ERROR;
2466
2467 sp<HwModule> rSubmixModule;
2468 // examine each mix's route type
2469 for (size_t i = 0; i < mixes.size(); i++) {
2470 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2471 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2472 res = INVALID_OPERATION;
2473 break;
2474 }
2475 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2476 // Loop back through "remote submix"
2477 if (rSubmixModule == 0) {
2478 for (size_t j = 0; i < mHwModules.size(); j++) {
2479 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2480 && mHwModules[j]->mHandle != 0) {
2481 rSubmixModule = mHwModules[j];
2482 break;
2483 }
2484 }
2485 }
2486
2487 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
2488
2489 if (rSubmixModule == 0) {
2490 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2491 res = INVALID_OPERATION;
2492 break;
2493 }
2494
2495 String8 address = mixes[i].mDeviceAddress;
2496
2497 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
2498 ALOGE(" Error registering mix %zu for address %s", i, address.string());
2499 res = INVALID_OPERATION;
2500 break;
2501 }
2502 audio_config_t outputConfig = mixes[i].mFormat;
2503 audio_config_t inputConfig = mixes[i].mFormat;
2504 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2505 // stereo and let audio flinger do the channel conversion if needed.
2506 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2507 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2508 rSubmixModule->addOutputProfile(address, &outputConfig,
2509 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2510 rSubmixModule->addInputProfile(address, &inputConfig,
2511 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2512
2513 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2514 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2515 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2516 address.string(), "remote-submix");
2517 } else {
2518 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2519 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2520 address.string(), "remote-submix");
2521 }
2522 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2523 String8 address = mixes[i].mDeviceAddress;
2524 audio_devices_t device = mixes[i].mDeviceType;
2525 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2526 i, mixes.size(), device, address.string());
2527
2528 bool foundOutput = false;
2529 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2530 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2531 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2532 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2533 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2534 && (patch->mPatch.sinks[0].ext.device.type == device)
2535 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2536 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
2537 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2538 res = INVALID_OPERATION;
2539 } else {
2540 foundOutput = true;
2541 }
2542 break;
2543 }
2544 }
2545
2546 if (res != NO_ERROR) {
2547 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
2548 i, device, address.string());
2549 res = INVALID_OPERATION;
2550 break;
2551 } else if (!foundOutput) {
2552 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2553 i, device, address.string());
2554 res = INVALID_OPERATION;
2555 break;
2556 }
2557 }
2558 }
2559 if (res != NO_ERROR) {
2560 unregisterPolicyMixes(mixes);
2561 }
2562 return res;
2563 }
2564
unregisterPolicyMixes(Vector<AudioMix> mixes)2565 status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2566 {
2567 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
2568 status_t res = NO_ERROR;
2569 sp<HwModule> rSubmixModule;
2570 // examine each mix's route type
2571 for (size_t i = 0; i < mixes.size(); i++) {
2572 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2573
2574 if (rSubmixModule == 0) {
2575 for (size_t j = 0; i < mHwModules.size(); j++) {
2576 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2577 && mHwModules[j]->mHandle != 0) {
2578 rSubmixModule = mHwModules[j];
2579 break;
2580 }
2581 }
2582 }
2583 if (rSubmixModule == 0) {
2584 res = INVALID_OPERATION;
2585 continue;
2586 }
2587
2588 String8 address = mixes[i].mDeviceAddress;
2589
2590 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2591 res = INVALID_OPERATION;
2592 continue;
2593 }
2594
2595 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2596 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2597 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2598 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2599 address.string(), "remote-submix");
2600 }
2601 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2602 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2603 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2604 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2605 address.string(), "remote-submix");
2606 }
2607 rSubmixModule->removeOutputProfile(address);
2608 rSubmixModule->removeInputProfile(address);
2609
2610 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2611 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2612 res = INVALID_OPERATION;
2613 continue;
2614 }
2615 }
2616 }
2617 return res;
2618 }
2619
2620
dump(int fd)2621 status_t AudioPolicyManager::dump(int fd)
2622 {
2623 const size_t SIZE = 256;
2624 char buffer[SIZE];
2625 String8 result;
2626
2627 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2628 result.append(buffer);
2629
2630 snprintf(buffer, SIZE, " Primary Output: %d\n",
2631 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
2632 result.append(buffer);
2633 std::string stateLiteral;
2634 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2635 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
2636 result.append(buffer);
2637 snprintf(buffer, SIZE, " Force use for communications %d\n",
2638 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
2639 result.append(buffer);
2640 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
2641 result.append(buffer);
2642 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
2643 result.append(buffer);
2644 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
2645 result.append(buffer);
2646 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
2647 result.append(buffer);
2648 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2649 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
2650 result.append(buffer);
2651 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2652 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2653 result.append(buffer);
2654 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2655 result.append(buffer);
2656 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2657 result.append(buffer);
2658
2659 write(fd, result.string(), result.size());
2660
2661 mAvailableOutputDevices.dump(fd, String8("Available output"));
2662 mAvailableInputDevices.dump(fd, String8("Available input"));
2663 mHwModules.dump(fd);
2664 mOutputs.dump(fd);
2665 mInputs.dump(fd);
2666 mVolumeCurves->dump(fd);
2667 mEffects.dump(fd);
2668 mAudioPatches.dump(fd);
2669 mPolicyMixes.dump(fd);
2670
2671 return NO_ERROR;
2672 }
2673
2674 // This function checks for the parameters which can be offloaded.
2675 // This can be enhanced depending on the capability of the DSP and policy
2676 // of the system.
isOffloadSupported(const audio_offload_info_t & offloadInfo)2677 bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
2678 {
2679 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
2680 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
2681 offloadInfo.sample_rate, offloadInfo.channel_mask,
2682 offloadInfo.format,
2683 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2684 offloadInfo.has_video);
2685
2686 if (mMasterMono) {
2687 return false; // no offloading if mono is set.
2688 }
2689
2690 // Check if offload has been disabled
2691 char propValue[PROPERTY_VALUE_MAX];
2692 if (property_get("audio.offload.disable", propValue, "0")) {
2693 if (atoi(propValue) != 0) {
2694 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2695 return false;
2696 }
2697 }
2698
2699 // Check if stream type is music, then only allow offload as of now.
2700 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2701 {
2702 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2703 return false;
2704 }
2705
2706 //TODO: enable audio offloading with video when ready
2707 const bool allowOffloadWithVideo =
2708 property_get_bool("audio.offload.video", false /* default_value */);
2709 if (offloadInfo.has_video && !allowOffloadWithVideo) {
2710 ALOGV("isOffloadSupported: has_video == true, returning false");
2711 return false;
2712 }
2713
2714 //If duration is less than minimum value defined in property, return false
2715 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2716 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2717 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2718 return false;
2719 }
2720 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2721 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2722 return false;
2723 }
2724
2725 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2726 // creating an offloaded track and tearing it down immediately after start when audioflinger
2727 // detects there is an active non offloadable effect.
2728 // FIXME: We should check the audio session here but we do not have it in this context.
2729 // This may prevent offloading in rare situations where effects are left active by apps
2730 // in the background.
2731 if (mEffects.isNonOffloadableEffectEnabled()) {
2732 return false;
2733 }
2734
2735 // See if there is a profile to support this.
2736 // AUDIO_DEVICE_NONE
2737 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
2738 offloadInfo.sample_rate,
2739 offloadInfo.format,
2740 offloadInfo.channel_mask,
2741 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
2742 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2743 return (profile != 0);
2744 }
2745
listAudioPorts(audio_port_role_t role,audio_port_type_t type,unsigned int * num_ports,struct audio_port * ports,unsigned int * generation)2746 status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2747 audio_port_type_t type,
2748 unsigned int *num_ports,
2749 struct audio_port *ports,
2750 unsigned int *generation)
2751 {
2752 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2753 generation == NULL) {
2754 return BAD_VALUE;
2755 }
2756 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2757 if (ports == NULL) {
2758 *num_ports = 0;
2759 }
2760
2761 size_t portsWritten = 0;
2762 size_t portsMax = *num_ports;
2763 *num_ports = 0;
2764 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2765 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2766 // as they are used by stub HALs by convention
2767 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2768 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2769 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2770 continue;
2771 }
2772 if (portsWritten < portsMax) {
2773 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2774 }
2775 (*num_ports)++;
2776 }
2777 }
2778 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2779 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2780 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2781 continue;
2782 }
2783 if (portsWritten < portsMax) {
2784 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2785 }
2786 (*num_ports)++;
2787 }
2788 }
2789 }
2790 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2791 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2792 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2793 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2794 }
2795 *num_ports += mInputs.size();
2796 }
2797 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2798 size_t numOutputs = 0;
2799 for (size_t i = 0; i < mOutputs.size(); i++) {
2800 if (!mOutputs[i]->isDuplicated()) {
2801 numOutputs++;
2802 if (portsWritten < portsMax) {
2803 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2804 }
2805 }
2806 }
2807 *num_ports += numOutputs;
2808 }
2809 }
2810 *generation = curAudioPortGeneration();
2811 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
2812 return NO_ERROR;
2813 }
2814
getAudioPort(struct audio_port * port __unused)2815 status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2816 {
2817 return NO_ERROR;
2818 }
2819
createAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle,uid_t uid)2820 status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2821 audio_patch_handle_t *handle,
2822 uid_t uid)
2823 {
2824 ALOGV("createAudioPatch()");
2825
2826 if (handle == NULL || patch == NULL) {
2827 return BAD_VALUE;
2828 }
2829 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2830
2831 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2832 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2833 return BAD_VALUE;
2834 }
2835 // only one source per audio patch supported for now
2836 if (patch->num_sources > 1) {
2837 return INVALID_OPERATION;
2838 }
2839
2840 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
2841 return INVALID_OPERATION;
2842 }
2843 for (size_t i = 0; i < patch->num_sinks; i++) {
2844 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2845 return INVALID_OPERATION;
2846 }
2847 }
2848
2849 sp<AudioPatch> patchDesc;
2850 ssize_t index = mAudioPatches.indexOfKey(*handle);
2851
2852 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2853 patch->sources[0].role,
2854 patch->sources[0].type);
2855 #if LOG_NDEBUG == 0
2856 for (size_t i = 0; i < patch->num_sinks; i++) {
2857 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
2858 patch->sinks[i].role,
2859 patch->sinks[i].type);
2860 }
2861 #endif
2862
2863 if (index >= 0) {
2864 patchDesc = mAudioPatches.valueAt(index);
2865 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2866 mUidCached, patchDesc->mUid, uid);
2867 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2868 return INVALID_OPERATION;
2869 }
2870 } else {
2871 *handle = AUDIO_PATCH_HANDLE_NONE;
2872 }
2873
2874 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
2875 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
2876 if (outputDesc == NULL) {
2877 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2878 return BAD_VALUE;
2879 }
2880 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2881 outputDesc->mIoHandle);
2882 if (patchDesc != 0) {
2883 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2884 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2885 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2886 return BAD_VALUE;
2887 }
2888 }
2889 DeviceVector devices;
2890 for (size_t i = 0; i < patch->num_sinks; i++) {
2891 // Only support mix to devices connection
2892 // TODO add support for mix to mix connection
2893 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2894 ALOGV("createAudioPatch() source mix but sink is not a device");
2895 return INVALID_OPERATION;
2896 }
2897 sp<DeviceDescriptor> devDesc =
2898 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2899 if (devDesc == 0) {
2900 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2901 return BAD_VALUE;
2902 }
2903
2904 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
2905 devDesc->mAddress,
2906 patch->sources[0].sample_rate,
2907 NULL, // updatedSamplingRate
2908 patch->sources[0].format,
2909 NULL, // updatedFormat
2910 patch->sources[0].channel_mask,
2911 NULL, // updatedChannelMask
2912 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2913 ALOGV("createAudioPatch() profile not supported for device %08x",
2914 devDesc->type());
2915 return INVALID_OPERATION;
2916 }
2917 devices.add(devDesc);
2918 }
2919 if (devices.size() == 0) {
2920 return INVALID_OPERATION;
2921 }
2922
2923 // TODO: reconfigure output format and channels here
2924 ALOGV("createAudioPatch() setting device %08x on output %d",
2925 devices.types(), outputDesc->mIoHandle);
2926 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
2927 index = mAudioPatches.indexOfKey(*handle);
2928 if (index >= 0) {
2929 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2930 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2931 }
2932 patchDesc = mAudioPatches.valueAt(index);
2933 patchDesc->mUid = uid;
2934 ALOGV("createAudioPatch() success");
2935 } else {
2936 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2937 return INVALID_OPERATION;
2938 }
2939 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2940 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2941 // input device to input mix connection
2942 // only one sink supported when connecting an input device to a mix
2943 if (patch->num_sinks > 1) {
2944 return INVALID_OPERATION;
2945 }
2946 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
2947 if (inputDesc == NULL) {
2948 return BAD_VALUE;
2949 }
2950 if (patchDesc != 0) {
2951 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2952 return BAD_VALUE;
2953 }
2954 }
2955 sp<DeviceDescriptor> devDesc =
2956 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2957 if (devDesc == 0) {
2958 return BAD_VALUE;
2959 }
2960
2961 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
2962 devDesc->mAddress,
2963 patch->sinks[0].sample_rate,
2964 NULL, /*updatedSampleRate*/
2965 patch->sinks[0].format,
2966 NULL, /*updatedFormat*/
2967 patch->sinks[0].channel_mask,
2968 NULL, /*updatedChannelMask*/
2969 // FIXME for the parameter type,
2970 // and the NONE
2971 (audio_output_flags_t)
2972 AUDIO_INPUT_FLAG_NONE)) {
2973 return INVALID_OPERATION;
2974 }
2975 // TODO: reconfigure output format and channels here
2976 ALOGV("createAudioPatch() setting device %08x on output %d",
2977 devDesc->type(), inputDesc->mIoHandle);
2978 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
2979 index = mAudioPatches.indexOfKey(*handle);
2980 if (index >= 0) {
2981 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2982 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2983 }
2984 patchDesc = mAudioPatches.valueAt(index);
2985 patchDesc->mUid = uid;
2986 ALOGV("createAudioPatch() success");
2987 } else {
2988 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2989 return INVALID_OPERATION;
2990 }
2991 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2992 // device to device connection
2993 if (patchDesc != 0) {
2994 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2995 return BAD_VALUE;
2996 }
2997 }
2998 sp<DeviceDescriptor> srcDeviceDesc =
2999 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3000 if (srcDeviceDesc == 0) {
3001 return BAD_VALUE;
3002 }
3003
3004 //update source and sink with our own data as the data passed in the patch may
3005 // be incomplete.
3006 struct audio_patch newPatch = *patch;
3007 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
3008
3009 for (size_t i = 0; i < patch->num_sinks; i++) {
3010 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3011 ALOGV("createAudioPatch() source device but one sink is not a device");
3012 return INVALID_OPERATION;
3013 }
3014
3015 sp<DeviceDescriptor> sinkDeviceDesc =
3016 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3017 if (sinkDeviceDesc == 0) {
3018 return BAD_VALUE;
3019 }
3020 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3021
3022 // create a software bridge in PatchPanel if:
3023 // - source and sink devices are on differnt HW modules OR
3024 // - audio HAL version is < 3.0
3025 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
3026 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
3027 // support only one sink device for now to simplify output selection logic
3028 if (patch->num_sinks > 1) {
3029 return INVALID_OPERATION;
3030 }
3031 SortedVector<audio_io_handle_t> outputs =
3032 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
3033 // if the sink device is reachable via an opened output stream, request to go via
3034 // this output stream by adding a second source to the patch description
3035 audio_io_handle_t output = selectOutput(outputs,
3036 AUDIO_OUTPUT_FLAG_NONE,
3037 AUDIO_FORMAT_INVALID);
3038 if (output != AUDIO_IO_HANDLE_NONE) {
3039 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3040 if (outputDesc->isDuplicated()) {
3041 return INVALID_OPERATION;
3042 }
3043 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
3044 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
3045 newPatch.num_sources = 2;
3046 }
3047 }
3048 }
3049 // TODO: check from routing capabilities in config file and other conflicting patches
3050
3051 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3052 if (index >= 0) {
3053 afPatchHandle = patchDesc->mAfPatchHandle;
3054 }
3055
3056 status_t status = mpClientInterface->createAudioPatch(&newPatch,
3057 &afPatchHandle,
3058 0);
3059 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
3060 status, afPatchHandle);
3061 if (status == NO_ERROR) {
3062 if (index < 0) {
3063 patchDesc = new AudioPatch(&newPatch, uid);
3064 addAudioPatch(patchDesc->mHandle, patchDesc);
3065 } else {
3066 patchDesc->mPatch = newPatch;
3067 }
3068 patchDesc->mAfPatchHandle = afPatchHandle;
3069 *handle = patchDesc->mHandle;
3070 nextAudioPortGeneration();
3071 mpClientInterface->onAudioPatchListUpdate();
3072 } else {
3073 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3074 status);
3075 return INVALID_OPERATION;
3076 }
3077 } else {
3078 return BAD_VALUE;
3079 }
3080 } else {
3081 return BAD_VALUE;
3082 }
3083 return NO_ERROR;
3084 }
3085
releaseAudioPatch(audio_patch_handle_t handle,uid_t uid)3086 status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3087 uid_t uid)
3088 {
3089 ALOGV("releaseAudioPatch() patch %d", handle);
3090
3091 ssize_t index = mAudioPatches.indexOfKey(handle);
3092
3093 if (index < 0) {
3094 return BAD_VALUE;
3095 }
3096 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3097 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3098 mUidCached, patchDesc->mUid, uid);
3099 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3100 return INVALID_OPERATION;
3101 }
3102
3103 struct audio_patch *patch = &patchDesc->mPatch;
3104 patchDesc->mUid = mUidCached;
3105 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
3106 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
3107 if (outputDesc == NULL) {
3108 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3109 return BAD_VALUE;
3110 }
3111
3112 setOutputDevice(outputDesc,
3113 getNewOutputDevice(outputDesc, true /*fromCache*/),
3114 true,
3115 0,
3116 NULL);
3117 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3118 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3119 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
3120 if (inputDesc == NULL) {
3121 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3122 return BAD_VALUE;
3123 }
3124 setInputDevice(inputDesc->mIoHandle,
3125 getNewInputDevice(inputDesc),
3126 true,
3127 NULL);
3128 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3129 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3130 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3131 status, patchDesc->mAfPatchHandle);
3132 removeAudioPatch(patchDesc->mHandle);
3133 nextAudioPortGeneration();
3134 mpClientInterface->onAudioPatchListUpdate();
3135 } else {
3136 return BAD_VALUE;
3137 }
3138 } else {
3139 return BAD_VALUE;
3140 }
3141 return NO_ERROR;
3142 }
3143
listAudioPatches(unsigned int * num_patches,struct audio_patch * patches,unsigned int * generation)3144 status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3145 struct audio_patch *patches,
3146 unsigned int *generation)
3147 {
3148 if (generation == NULL) {
3149 return BAD_VALUE;
3150 }
3151 *generation = curAudioPortGeneration();
3152 return mAudioPatches.listAudioPatches(num_patches, patches);
3153 }
3154
setAudioPortConfig(const struct audio_port_config * config)3155 status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
3156 {
3157 ALOGV("setAudioPortConfig()");
3158
3159 if (config == NULL) {
3160 return BAD_VALUE;
3161 }
3162 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3163 // Only support gain configuration for now
3164 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3165 return INVALID_OPERATION;
3166 }
3167
3168 sp<AudioPortConfig> audioPortConfig;
3169 if (config->type == AUDIO_PORT_TYPE_MIX) {
3170 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3171 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
3172 if (outputDesc == NULL) {
3173 return BAD_VALUE;
3174 }
3175 ALOG_ASSERT(!outputDesc->isDuplicated(),
3176 "setAudioPortConfig() called on duplicated output %d",
3177 outputDesc->mIoHandle);
3178 audioPortConfig = outputDesc;
3179 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3180 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
3181 if (inputDesc == NULL) {
3182 return BAD_VALUE;
3183 }
3184 audioPortConfig = inputDesc;
3185 } else {
3186 return BAD_VALUE;
3187 }
3188 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3189 sp<DeviceDescriptor> deviceDesc;
3190 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3191 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3192 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3193 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3194 } else {
3195 return BAD_VALUE;
3196 }
3197 if (deviceDesc == NULL) {
3198 return BAD_VALUE;
3199 }
3200 audioPortConfig = deviceDesc;
3201 } else {
3202 return BAD_VALUE;
3203 }
3204
3205 struct audio_port_config backupConfig;
3206 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3207 if (status == NO_ERROR) {
3208 struct audio_port_config newConfig;
3209 audioPortConfig->toAudioPortConfig(&newConfig, config);
3210 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
3211 }
3212 if (status != NO_ERROR) {
3213 audioPortConfig->applyAudioPortConfig(&backupConfig);
3214 }
3215
3216 return status;
3217 }
3218
releaseResourcesForUid(uid_t uid)3219 void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3220 {
3221 clearAudioSources(uid);
3222 clearAudioPatches(uid);
3223 clearSessionRoutes(uid);
3224 }
3225
clearAudioPatches(uid_t uid)3226 void AudioPolicyManager::clearAudioPatches(uid_t uid)
3227 {
3228 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
3229 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3230 if (patchDesc->mUid == uid) {
3231 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
3232 }
3233 }
3234 }
3235
checkStrategyRoute(routing_strategy strategy,audio_io_handle_t ouptutToSkip)3236 void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3237 audio_io_handle_t ouptutToSkip)
3238 {
3239 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3240 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3241 for (size_t j = 0; j < mOutputs.size(); j++) {
3242 if (mOutputs.keyAt(j) == ouptutToSkip) {
3243 continue;
3244 }
3245 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3246 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3247 continue;
3248 }
3249 // If the default device for this strategy is on another output mix,
3250 // invalidate all tracks in this strategy to force re connection.
3251 // Otherwise select new device on the output mix.
3252 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
3253 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
3254 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3255 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3256 }
3257 }
3258 } else {
3259 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3260 setOutputDevice(outputDesc, newDevice, false);
3261 }
3262 }
3263 }
3264
clearSessionRoutes(uid_t uid)3265 void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3266 {
3267 // remove output routes associated with this uid
3268 SortedVector<routing_strategy> affectedStrategies;
3269 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3270 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3271 if (route->mUid == uid) {
3272 mOutputRoutes.removeItemsAt(i);
3273 if (route->mDeviceDescriptor != 0) {
3274 affectedStrategies.add(getStrategy(route->mStreamType));
3275 }
3276 }
3277 }
3278 // reroute outputs if necessary
3279 for (size_t i = 0; i < affectedStrategies.size(); i++) {
3280 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
3281 }
3282
3283 // remove input routes associated with this uid
3284 SortedVector<audio_source_t> affectedSources;
3285 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3286 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3287 if (route->mUid == uid) {
3288 mInputRoutes.removeItemsAt(i);
3289 if (route->mDeviceDescriptor != 0) {
3290 affectedSources.add(route->mSource);
3291 }
3292 }
3293 }
3294 // reroute inputs if necessary
3295 SortedVector<audio_io_handle_t> inputsToClose;
3296 for (size_t i = 0; i < mInputs.size(); i++) {
3297 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3298 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
3299 inputsToClose.add(inputDesc->mIoHandle);
3300 }
3301 }
3302 for (size_t i = 0; i < inputsToClose.size(); i++) {
3303 closeInput(inputsToClose[i]);
3304 }
3305 }
3306
clearAudioSources(uid_t uid)3307 void AudioPolicyManager::clearAudioSources(uid_t uid)
3308 {
3309 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3310 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3311 if (sourceDesc->mUid == uid) {
3312 stopAudioSource(mAudioSources.keyAt(i));
3313 }
3314 }
3315 }
3316
acquireSoundTriggerSession(audio_session_t * session,audio_io_handle_t * ioHandle,audio_devices_t * device)3317 status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3318 audio_io_handle_t *ioHandle,
3319 audio_devices_t *device)
3320 {
3321 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3322 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
3323 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
3324
3325 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
3326 }
3327
startAudioSource(const struct audio_port_config * source,const audio_attributes_t * attributes,audio_patch_handle_t * handle,uid_t uid)3328 status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3329 const audio_attributes_t *attributes,
3330 audio_patch_handle_t *handle,
3331 uid_t uid)
3332 {
3333 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3334 if (source == NULL || attributes == NULL || handle == NULL) {
3335 return BAD_VALUE;
3336 }
3337
3338 *handle = AUDIO_PATCH_HANDLE_NONE;
3339
3340 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3341 source->type != AUDIO_PORT_TYPE_DEVICE) {
3342 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3343 return INVALID_OPERATION;
3344 }
3345
3346 sp<DeviceDescriptor> srcDeviceDesc =
3347 mAvailableInputDevices.getDevice(source->ext.device.type,
3348 String8(source->ext.device.address));
3349 if (srcDeviceDesc == 0) {
3350 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3351 return BAD_VALUE;
3352 }
3353 sp<AudioSourceDescriptor> sourceDesc =
3354 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3355
3356 struct audio_patch dummyPatch;
3357 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3358 sourceDesc->mPatchDesc = patchDesc;
3359
3360 status_t status = connectAudioSource(sourceDesc);
3361 if (status == NO_ERROR) {
3362 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3363 *handle = sourceDesc->getHandle();
3364 }
3365 return status;
3366 }
3367
connectAudioSource(const sp<AudioSourceDescriptor> & sourceDesc)3368 status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3369 {
3370 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3371
3372 // make sure we only have one patch per source.
3373 disconnectAudioSource(sourceDesc);
3374
3375 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3376 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
3377 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3378
3379 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3380 sp<DeviceDescriptor> sinkDeviceDesc =
3381 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3382
3383 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3384 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3385
3386 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3387 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
3388 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
3389 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3390 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3391 // create patch between src device and output device
3392 // create Hwoutput and add to mHwOutputs
3393 } else {
3394 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3395 audio_io_handle_t output =
3396 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3397 if (output == AUDIO_IO_HANDLE_NONE) {
3398 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3399 return INVALID_OPERATION;
3400 }
3401 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3402 if (outputDesc->isDuplicated()) {
3403 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3404 return INVALID_OPERATION;
3405 }
3406 // create a special patch with no sink and two sources:
3407 // - the second source indicates to PatchPanel through which output mix this patch should
3408 // be connected as well as the stream type for volume control
3409 // - the sink is defined by whatever output device is currently selected for the output
3410 // though which this patch is routed.
3411 patch->num_sinks = 0;
3412 patch->num_sources = 2;
3413 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3414 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3415 patch->sources[1].ext.mix.usecase.stream = stream;
3416 status_t status = mpClientInterface->createAudioPatch(patch,
3417 &afPatchHandle,
3418 0);
3419 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3420 status, afPatchHandle);
3421 if (status != NO_ERROR) {
3422 ALOGW("%s patch panel could not connect device patch, error %d",
3423 __FUNCTION__, status);
3424 return INVALID_OPERATION;
3425 }
3426 uint32_t delayMs = 0;
3427 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
3428
3429 if (status != NO_ERROR) {
3430 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3431 return status;
3432 }
3433 sourceDesc->mSwOutput = outputDesc;
3434 if (delayMs != 0) {
3435 usleep(delayMs * 1000);
3436 }
3437 }
3438
3439 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3440 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3441
3442 return NO_ERROR;
3443 }
3444
stopAudioSource(audio_patch_handle_t handle __unused)3445 status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
3446 {
3447 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3448 ALOGV("%s handle %d", __FUNCTION__, handle);
3449 if (sourceDesc == 0) {
3450 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3451 return BAD_VALUE;
3452 }
3453 status_t status = disconnectAudioSource(sourceDesc);
3454
3455 mAudioSources.removeItem(handle);
3456 return status;
3457 }
3458
setMasterMono(bool mono)3459 status_t AudioPolicyManager::setMasterMono(bool mono)
3460 {
3461 if (mMasterMono == mono) {
3462 return NO_ERROR;
3463 }
3464 mMasterMono = mono;
3465 // if enabling mono we close all offloaded devices, which will invalidate the
3466 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3467 // for recreating the new AudioTrack as non-offloaded PCM.
3468 //
3469 // If disabling mono, we leave all tracks as is: we don't know which clients
3470 // and tracks are able to be recreated as offloaded. The next "song" should
3471 // play back offloaded.
3472 if (mMasterMono) {
3473 Vector<audio_io_handle_t> offloaded;
3474 for (size_t i = 0; i < mOutputs.size(); ++i) {
3475 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3476 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3477 offloaded.push(desc->mIoHandle);
3478 }
3479 }
3480 for (size_t i = 0; i < offloaded.size(); ++i) {
3481 closeOutput(offloaded[i]);
3482 }
3483 }
3484 // update master mono for all remaining outputs
3485 for (size_t i = 0; i < mOutputs.size(); ++i) {
3486 updateMono(mOutputs.keyAt(i));
3487 }
3488 return NO_ERROR;
3489 }
3490
getMasterMono(bool * mono)3491 status_t AudioPolicyManager::getMasterMono(bool *mono)
3492 {
3493 *mono = mMasterMono;
3494 return NO_ERROR;
3495 }
3496
getStreamVolumeDB(audio_stream_type_t stream,int index,audio_devices_t device)3497 float AudioPolicyManager::getStreamVolumeDB(
3498 audio_stream_type_t stream, int index, audio_devices_t device)
3499 {
3500 return computeVolume(stream, index, device);
3501 }
3502
disconnectAudioSource(const sp<AudioSourceDescriptor> & sourceDesc)3503 status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3504 {
3505 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3506
3507 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3508 if (patchDesc == 0) {
3509 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3510 sourceDesc->mPatchDesc->mHandle);
3511 return BAD_VALUE;
3512 }
3513 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3514
3515 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
3516 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3517 if (swOutputDesc != 0) {
3518 stopSource(swOutputDesc, stream, false);
3519 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3520 } else {
3521 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3522 if (hwOutputDesc != 0) {
3523 // release patch between src device and output device
3524 // close Hwoutput and remove from mHwOutputs
3525 } else {
3526 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3527 }
3528 }
3529 return NO_ERROR;
3530 }
3531
getSourceForStrategyOnOutput(audio_io_handle_t output,routing_strategy strategy)3532 sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3533 audio_io_handle_t output, routing_strategy strategy)
3534 {
3535 sp<AudioSourceDescriptor> source;
3536 for (size_t i = 0; i < mAudioSources.size(); i++) {
3537 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3538 routing_strategy sourceStrategy =
3539 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3540 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3541 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3542 source = sourceDesc;
3543 break;
3544 }
3545 }
3546 return source;
3547 }
3548
3549 // ----------------------------------------------------------------------------
3550 // AudioPolicyManager
3551 // ----------------------------------------------------------------------------
nextAudioPortGeneration()3552 uint32_t AudioPolicyManager::nextAudioPortGeneration()
3553 {
3554 return android_atomic_inc(&mAudioPortGeneration);
3555 }
3556
3557 #ifdef USE_XML_AUDIO_POLICY_CONF
3558 // Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3559 static const char *kConfigLocationList[] =
3560 {"/odm/etc", "/vendor/etc", "/system/etc"};
3561 static const int kConfigLocationListSize =
3562 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3563
deserializeAudioPolicyXmlConfig(AudioPolicyConfig & config)3564 static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3565 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
3566 status_t ret;
3567
3568 for (int i = 0; i < kConfigLocationListSize; i++) {
3569 PolicySerializer serializer;
3570 snprintf(audioPolicyXmlConfigFile,
3571 sizeof(audioPolicyXmlConfigFile),
3572 "%s/%s",
3573 kConfigLocationList[i],
3574 AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3575 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3576 if (ret == NO_ERROR) {
3577 break;
3578 }
3579 }
3580 return ret;
3581 }
3582 #endif
3583
AudioPolicyManager(AudioPolicyClientInterface * clientInterface)3584 AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3585 :
3586 #ifdef AUDIO_POLICY_TEST
3587 Thread(false),
3588 #endif //AUDIO_POLICY_TEST
3589 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
3590 mA2dpSuspended(false),
3591 mAudioPortGeneration(1),
3592 mBeaconMuteRefCount(0),
3593 mBeaconPlayingRefCount(0),
3594 mBeaconMuted(false),
3595 mTtsOutputAvailable(false),
3596 mMasterMono(false),
3597 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3598 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
3599 {
3600 mUidCached = getuid();
3601 mpClientInterface = clientInterface;
3602
3603 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3604 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3605 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3606 bool speakerDrcEnabled = false;
3607
3608 #ifdef USE_XML_AUDIO_POLICY_CONF
3609 mVolumeCurves = new VolumeCurvesCollection();
3610 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3611 mDefaultOutputDevice, speakerDrcEnabled,
3612 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3613 if (deserializeAudioPolicyXmlConfig(config) != NO_ERROR) {
3614 #else
3615 mVolumeCurves = new StreamDescriptorCollection();
3616 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3617 mDefaultOutputDevice, speakerDrcEnabled);
3618 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3619 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3620 #endif
3621 ALOGE("could not load audio policy configuration file, setting defaults");
3622 config.setDefault();
3623 }
3624 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3625 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3626
3627 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
3628 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3629 if (!engineInstance) {
3630 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3631 return;
3632 }
3633 // Retrieve the Policy Manager Interface
3634 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3635 if (mEngine == NULL) {
3636 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3637 return;
3638 }
3639 mEngine->setObserver(this);
3640 status_t status = mEngine->initCheck();
3641 (void) status;
3642 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3643
3644 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
3645 // open all output streams needed to access attached devices
3646 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3647 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
3648 for (size_t i = 0; i < mHwModules.size(); i++) {
3649 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
3650 if (mHwModules[i]->mHandle == 0) {
3651 ALOGW("could not open HW module %s", mHwModules[i]->getName());
3652 continue;
3653 }
3654 // open all output streams needed to access attached devices
3655 // except for direct output streams that are only opened when they are actually
3656 // required by an app.
3657 // This also validates mAvailableOutputDevices list
3658 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3659 {
3660 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
3661
3662 if (!outProfile->hasSupportedDevices()) {
3663 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
3664 continue;
3665 }
3666 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
3667 mTtsOutputAvailable = true;
3668 }
3669
3670 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
3671 continue;
3672 }
3673 audio_devices_t profileType = outProfile->getSupportedDevicesType();
3674 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3675 profileType = mDefaultOutputDevice->type();
3676 } else {
3677 // chose first device present in profile's SupportedDevices also part of
3678 // outputDeviceTypes
3679 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
3680 }
3681 if ((profileType & outputDeviceTypes) == 0) {
3682 continue;
3683 }
3684 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3685 mpClientInterface);
3686 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3687 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3688 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3689 : String8("");
3690
3691 outputDesc->mDevice = profileType;
3692 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3693 config.sample_rate = outputDesc->mSamplingRate;
3694 config.channel_mask = outputDesc->mChannelMask;
3695 config.format = outputDesc->mFormat;
3696 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3697 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
3698 &output,
3699 &config,
3700 &outputDesc->mDevice,
3701 address,
3702 &outputDesc->mLatency,
3703 outputDesc->mFlags);
3704
3705 if (status != NO_ERROR) {
3706 ALOGW("Cannot open output stream for device %08x on hw module %s",
3707 outputDesc->mDevice,
3708 mHwModules[i]->getName());
3709 } else {
3710 outputDesc->mSamplingRate = config.sample_rate;
3711 outputDesc->mChannelMask = config.channel_mask;
3712 outputDesc->mFormat = config.format;
3713
3714 for (size_t k = 0; k < supportedDevices.size(); k++) {
3715 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
3716 // give a valid ID to an attached device once confirmed it is reachable
3717 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3718 mAvailableOutputDevices[index]->attach(mHwModules[i]);
3719 }
3720 }
3721 if (mPrimaryOutput == 0 &&
3722 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
3723 mPrimaryOutput = outputDesc;
3724 }
3725 addOutput(output, outputDesc);
3726 setOutputDevice(outputDesc,
3727 outputDesc->mDevice,
3728 true,
3729 0,
3730 NULL,
3731 address.string());
3732 }
3733 }
3734 // open input streams needed to access attached devices to validate
3735 // mAvailableInputDevices list
3736 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3737 {
3738 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
3739
3740 if (!inProfile->hasSupportedDevices()) {
3741 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
3742 continue;
3743 }
3744 // chose first device present in profile's SupportedDevices also part of
3745 // inputDeviceTypes
3746 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3747
3748 if ((profileType & inputDeviceTypes) == 0) {
3749 continue;
3750 }
3751 sp<AudioInputDescriptor> inputDesc =
3752 new AudioInputDescriptor(inProfile);
3753
3754 inputDesc->mDevice = profileType;
3755
3756 // find the address
3757 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3758 // the inputs vector must be of size 1, but we don't want to crash here
3759 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3760 : String8("");
3761 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3762 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3763
3764 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3765 config.sample_rate = inputDesc->mSamplingRate;
3766 config.channel_mask = inputDesc->mChannelMask;
3767 config.format = inputDesc->mFormat;
3768 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3769 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
3770 &input,
3771 &config,
3772 &inputDesc->mDevice,
3773 address,
3774 AUDIO_SOURCE_MIC,
3775 AUDIO_INPUT_FLAG_NONE);
3776
3777 if (status == NO_ERROR) {
3778 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3779 for (size_t k = 0; k < supportedDevices.size(); k++) {
3780 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
3781 // give a valid ID to an attached device once confirmed it is reachable
3782 if (index >= 0) {
3783 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3784 if (!devDesc->isAttached()) {
3785 devDesc->attach(mHwModules[i]);
3786 devDesc->importAudioPort(inProfile, true);
3787 }
3788 }
3789 }
3790 mpClientInterface->closeInput(input);
3791 } else {
3792 ALOGW("Cannot open input stream for device %08x on hw module %s",
3793 inputDesc->mDevice,
3794 mHwModules[i]->getName());
3795 }
3796 }
3797 }
3798 // make sure all attached devices have been allocated a unique ID
3799 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
3800 if (!mAvailableOutputDevices[i]->isAttached()) {
3801 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
3802 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3803 continue;
3804 }
3805 // The device is now validated and can be appended to the available devices of the engine
3806 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3807 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
3808 i++;
3809 }
3810 for (size_t i = 0; i < mAvailableInputDevices.size();) {
3811 if (!mAvailableInputDevices[i]->isAttached()) {
3812 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
3813 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3814 continue;
3815 }
3816 // The device is now validated and can be appended to the available devices of the engine
3817 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3818 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
3819 i++;
3820 }
3821 // make sure default device is reachable
3822 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
3823 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
3824 }
3825
3826 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3827
3828 updateDevicesAndOutputs();
3829
3830 #ifdef AUDIO_POLICY_TEST
3831 if (mPrimaryOutput != 0) {
3832 AudioParameter outputCmd = AudioParameter();
3833 outputCmd.addInt(String8("set_id"), 0);
3834 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
3835
3836 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3837 mTestSamplingRate = 44100;
3838 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3839 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
3840 mTestLatencyMs = 0;
3841 mCurOutput = 0;
3842 mDirectOutput = false;
3843 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3844 mTestOutputs[i] = 0;
3845 }
3846
3847 const size_t SIZE = 256;
3848 char buffer[SIZE];
3849 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3850 run(buffer, ANDROID_PRIORITY_AUDIO);
3851 }
3852 #endif //AUDIO_POLICY_TEST
3853 }
3854
3855 AudioPolicyManager::~AudioPolicyManager()
3856 {
3857 #ifdef AUDIO_POLICY_TEST
3858 exit();
3859 #endif //AUDIO_POLICY_TEST
3860 for (size_t i = 0; i < mOutputs.size(); i++) {
3861 mpClientInterface->closeOutput(mOutputs.keyAt(i));
3862 }
3863 for (size_t i = 0; i < mInputs.size(); i++) {
3864 mpClientInterface->closeInput(mInputs.keyAt(i));
3865 }
3866 mAvailableOutputDevices.clear();
3867 mAvailableInputDevices.clear();
3868 mOutputs.clear();
3869 mInputs.clear();
3870 mHwModules.clear();
3871 }
3872
3873 status_t AudioPolicyManager::initCheck()
3874 {
3875 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
3876 }
3877
3878 #ifdef AUDIO_POLICY_TEST
3879 bool AudioPolicyManager::threadLoop()
3880 {
3881 ALOGV("entering threadLoop()");
3882 while (!exitPending())
3883 {
3884 String8 command;
3885 int valueInt;
3886 String8 value;
3887
3888 Mutex::Autolock _l(mLock);
3889 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3890
3891 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3892 AudioParameter param = AudioParameter(command);
3893
3894 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3895 valueInt != 0) {
3896 ALOGV("Test command %s received", command.string());
3897 String8 target;
3898 if (param.get(String8("target"), target) != NO_ERROR) {
3899 target = "Manager";
3900 }
3901 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3902 param.remove(String8("test_cmd_policy_output"));
3903 mCurOutput = valueInt;
3904 }
3905 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3906 param.remove(String8("test_cmd_policy_direct"));
3907 if (value == "false") {
3908 mDirectOutput = false;
3909 } else if (value == "true") {
3910 mDirectOutput = true;
3911 }
3912 }
3913 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3914 param.remove(String8("test_cmd_policy_input"));
3915 mTestInput = valueInt;
3916 }
3917
3918 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3919 param.remove(String8("test_cmd_policy_format"));
3920 int format = AUDIO_FORMAT_INVALID;
3921 if (value == "PCM 16 bits") {
3922 format = AUDIO_FORMAT_PCM_16_BIT;
3923 } else if (value == "PCM 8 bits") {
3924 format = AUDIO_FORMAT_PCM_8_BIT;
3925 } else if (value == "Compressed MP3") {
3926 format = AUDIO_FORMAT_MP3;
3927 }
3928 if (format != AUDIO_FORMAT_INVALID) {
3929 if (target == "Manager") {
3930 mTestFormat = format;
3931 } else if (mTestOutputs[mCurOutput] != 0) {
3932 AudioParameter outputParam = AudioParameter();
3933 outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
3934 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3935 }
3936 }
3937 }
3938 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3939 param.remove(String8("test_cmd_policy_channels"));
3940 int channels = 0;
3941
3942 if (value == "Channels Stereo") {
3943 channels = AUDIO_CHANNEL_OUT_STEREO;
3944 } else if (value == "Channels Mono") {
3945 channels = AUDIO_CHANNEL_OUT_MONO;
3946 }
3947 if (channels != 0) {
3948 if (target == "Manager") {
3949 mTestChannels = channels;
3950 } else if (mTestOutputs[mCurOutput] != 0) {
3951 AudioParameter outputParam = AudioParameter();
3952 outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
3953 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3954 }
3955 }
3956 }
3957 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3958 param.remove(String8("test_cmd_policy_sampleRate"));
3959 if (valueInt >= 0 && valueInt <= 96000) {
3960 int samplingRate = valueInt;
3961 if (target == "Manager") {
3962 mTestSamplingRate = samplingRate;
3963 } else if (mTestOutputs[mCurOutput] != 0) {
3964 AudioParameter outputParam = AudioParameter();
3965 outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
3966 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3967 }
3968 }
3969 }
3970
3971 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3972 param.remove(String8("test_cmd_policy_reopen"));
3973
3974 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
3975
3976 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
3977
3978 removeOutput(mPrimaryOutput->mIoHandle);
3979 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3980 mpClientInterface);
3981 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
3982 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3983 config.sample_rate = outputDesc->mSamplingRate;
3984 config.channel_mask = outputDesc->mChannelMask;
3985 config.format = outputDesc->mFormat;
3986 audio_io_handle_t handle;
3987 status_t status = mpClientInterface->openOutput(moduleHandle,
3988 &handle,
3989 &config,
3990 &outputDesc->mDevice,
3991 String8(""),
3992 &outputDesc->mLatency,
3993 outputDesc->mFlags);
3994 if (status != NO_ERROR) {
3995 ALOGE("Failed to reopen hardware output stream, "
3996 "samplingRate: %d, format %d, channels %d",
3997 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
3998 } else {
3999 outputDesc->mSamplingRate = config.sample_rate;
4000 outputDesc->mChannelMask = config.channel_mask;
4001 outputDesc->mFormat = config.format;
4002 mPrimaryOutput = outputDesc;
4003 AudioParameter outputCmd = AudioParameter();
4004 outputCmd.addInt(String8("set_id"), 0);
4005 mpClientInterface->setParameters(handle, outputCmd.toString());
4006 addOutput(handle, outputDesc);
4007 }
4008 }
4009
4010
4011 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
4012 }
4013 }
4014 return false;
4015 }
4016
4017 void AudioPolicyManager::exit()
4018 {
4019 {
4020 AutoMutex _l(mLock);
4021 requestExit();
4022 mWaitWorkCV.signal();
4023 }
4024 requestExitAndWait();
4025 }
4026
4027 int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
4028 {
4029 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
4030 if (output == mTestOutputs[i]) return i;
4031 }
4032 return 0;
4033 }
4034 #endif //AUDIO_POLICY_TEST
4035
4036 // ---
4037
4038 void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
4039 {
4040 outputDesc->setIoHandle(output);
4041 mOutputs.add(output, outputDesc);
4042 updateMono(output); // update mono status when adding to output list
4043 selectOutputForMusicEffects();
4044 nextAudioPortGeneration();
4045 }
4046
4047 void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4048 {
4049 mOutputs.removeItem(output);
4050 selectOutputForMusicEffects();
4051 }
4052
4053 void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
4054 {
4055 inputDesc->setIoHandle(input);
4056 mInputs.add(input, inputDesc);
4057 nextAudioPortGeneration();
4058 }
4059
4060 void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
4061 const audio_devices_t device /*in*/,
4062 const String8& address /*in*/,
4063 SortedVector<audio_io_handle_t>& outputs /*out*/) {
4064 sp<DeviceDescriptor> devDesc =
4065 desc->mProfile->getSupportedDeviceByAddress(device, address);
4066 if (devDesc != 0) {
4067 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4068 desc->mIoHandle, address.string());
4069 outputs.add(desc->mIoHandle);
4070 }
4071 }
4072
4073 status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
4074 audio_policy_dev_state_t state,
4075 SortedVector<audio_io_handle_t>& outputs,
4076 const String8& address)
4077 {
4078 audio_devices_t device = devDesc->type();
4079 sp<SwAudioOutputDescriptor> desc;
4080
4081 if (audio_device_is_digital(device)) {
4082 // erase all current sample rates, formats and channel masks
4083 devDesc->clearAudioProfiles();
4084 }
4085
4086 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4087 // first list already open outputs that can be routed to this device
4088 for (size_t i = 0; i < mOutputs.size(); i++) {
4089 desc = mOutputs.valueAt(i);
4090 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
4091 if (!device_distinguishes_on_address(device)) {
4092 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4093 outputs.add(mOutputs.keyAt(i));
4094 } else {
4095 ALOGV(" checking address match due to device 0x%x", device);
4096 findIoHandlesByAddress(desc, device, address, outputs);
4097 }
4098 }
4099 }
4100 // then look for output profiles that can be routed to this device
4101 SortedVector< sp<IOProfile> > profiles;
4102 for (size_t i = 0; i < mHwModules.size(); i++)
4103 {
4104 if (mHwModules[i]->mHandle == 0) {
4105 continue;
4106 }
4107 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4108 {
4109 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
4110 if (profile->supportDevice(device)) {
4111 if (!device_distinguishes_on_address(device) ||
4112 profile->supportDeviceAddress(address)) {
4113 profiles.add(profile);
4114 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
4115 }
4116 }
4117 }
4118 }
4119
4120 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
4121
4122 if (profiles.isEmpty() && outputs.isEmpty()) {
4123 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4124 return BAD_VALUE;
4125 }
4126
4127 // open outputs for matching profiles if needed. Direct outputs are also opened to
4128 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4129 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4130 sp<IOProfile> profile = profiles[profile_index];
4131
4132 // nothing to do if one output is already opened for this profile
4133 size_t j;
4134 for (j = 0; j < outputs.size(); j++) {
4135 desc = mOutputs.valueFor(outputs.itemAt(j));
4136 if (!desc->isDuplicated() && desc->mProfile == profile) {
4137 // matching profile: save the sample rates, format and channel masks supported
4138 // by the profile in our device descriptor
4139 if (audio_device_is_digital(device)) {
4140 devDesc->importAudioPort(profile);
4141 }
4142 break;
4143 }
4144 }
4145 if (j != outputs.size()) {
4146 continue;
4147 }
4148
4149 ALOGV("opening output for device %08x with params %s profile %p name %s",
4150 device, address.string(), profile.get(), profile->getName().string());
4151 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
4152 desc->mDevice = device;
4153 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4154 config.sample_rate = desc->mSamplingRate;
4155 config.channel_mask = desc->mChannelMask;
4156 config.format = desc->mFormat;
4157 config.offload_info.sample_rate = desc->mSamplingRate;
4158 config.offload_info.channel_mask = desc->mChannelMask;
4159 config.offload_info.format = desc->mFormat;
4160 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4161 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
4162 &output,
4163 &config,
4164 &desc->mDevice,
4165 address,
4166 &desc->mLatency,
4167 desc->mFlags);
4168 if (status == NO_ERROR) {
4169 desc->mSamplingRate = config.sample_rate;
4170 desc->mChannelMask = config.channel_mask;
4171 desc->mFormat = config.format;
4172
4173 // Here is where the out_set_parameters() for card & device gets called
4174 if (!address.isEmpty()) {
4175 char *param = audio_device_address_to_parameter(device, address);
4176 mpClientInterface->setParameters(output, String8(param));
4177 free(param);
4178 }
4179 updateAudioProfiles(device, output, profile->getAudioProfiles());
4180 if (!profile->hasValidAudioProfile()) {
4181 ALOGW("checkOutputsForDevice() missing param");
4182 mpClientInterface->closeOutput(output);
4183 output = AUDIO_IO_HANDLE_NONE;
4184 } else if (profile->hasDynamicAudioProfile()) {
4185 mpClientInterface->closeOutput(output);
4186 output = AUDIO_IO_HANDLE_NONE;
4187 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
4188 config.offload_info.sample_rate = config.sample_rate;
4189 config.offload_info.channel_mask = config.channel_mask;
4190 config.offload_info.format = config.format;
4191 status = mpClientInterface->openOutput(profile->getModuleHandle(),
4192 &output,
4193 &config,
4194 &desc->mDevice,
4195 address,
4196 &desc->mLatency,
4197 desc->mFlags);
4198 if (status == NO_ERROR) {
4199 desc->mSamplingRate = config.sample_rate;
4200 desc->mChannelMask = config.channel_mask;
4201 desc->mFormat = config.format;
4202 } else {
4203 output = AUDIO_IO_HANDLE_NONE;
4204 }
4205 }
4206
4207 if (output != AUDIO_IO_HANDLE_NONE) {
4208 addOutput(output, desc);
4209 if (device_distinguishes_on_address(device) && address != "0") {
4210 sp<AudioPolicyMix> policyMix;
4211 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
4212 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4213 address.string());
4214 }
4215 policyMix->setOutput(desc);
4216 desc->mPolicyMix = policyMix;
4217
4218 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4219 hasPrimaryOutput()) {
4220 // no duplicated output for direct outputs and
4221 // outputs used by dynamic policy mixes
4222 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
4223
4224 // set initial stream volume for device
4225 applyStreamVolumes(desc, device, 0, true);
4226
4227 //TODO: configure audio effect output stage here
4228
4229 // open a duplicating output thread for the new output and the primary output
4230 duplicatedOutput =
4231 mpClientInterface->openDuplicateOutput(output,
4232 mPrimaryOutput->mIoHandle);
4233 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
4234 // add duplicated output descriptor
4235 sp<SwAudioOutputDescriptor> dupOutputDesc =
4236 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4237 dupOutputDesc->mOutput1 = mPrimaryOutput;
4238 dupOutputDesc->mOutput2 = desc;
4239 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
4240 dupOutputDesc->mFormat = desc->mFormat;
4241 dupOutputDesc->mChannelMask = desc->mChannelMask;
4242 dupOutputDesc->mLatency = desc->mLatency;
4243 addOutput(duplicatedOutput, dupOutputDesc);
4244 applyStreamVolumes(dupOutputDesc, device, 0, true);
4245 } else {
4246 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
4247 mPrimaryOutput->mIoHandle, output);
4248 mpClientInterface->closeOutput(output);
4249 removeOutput(output);
4250 nextAudioPortGeneration();
4251 output = AUDIO_IO_HANDLE_NONE;
4252 }
4253 }
4254 }
4255 } else {
4256 output = AUDIO_IO_HANDLE_NONE;
4257 }
4258 if (output == AUDIO_IO_HANDLE_NONE) {
4259 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
4260 profiles.removeAt(profile_index);
4261 profile_index--;
4262 } else {
4263 outputs.add(output);
4264 // Load digital format info only for digital devices
4265 if (audio_device_is_digital(device)) {
4266 devDesc->importAudioPort(profile);
4267 }
4268
4269 if (device_distinguishes_on_address(device)) {
4270 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4271 device, address.string());
4272 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
4273 NULL/*patch handle*/, address.string());
4274 }
4275 ALOGV("checkOutputsForDevice(): adding output %d", output);
4276 }
4277 }
4278
4279 if (profiles.isEmpty()) {
4280 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4281 return BAD_VALUE;
4282 }
4283 } else { // Disconnect
4284 // check if one opened output is not needed any more after disconnecting one device
4285 for (size_t i = 0; i < mOutputs.size(); i++) {
4286 desc = mOutputs.valueAt(i);
4287 if (!desc->isDuplicated()) {
4288 // exact match on device
4289 if (device_distinguishes_on_address(device) &&
4290 (desc->supportedDevices() == device)) {
4291 findIoHandlesByAddress(desc, device, address, outputs);
4292 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
4293 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4294 mOutputs.keyAt(i));
4295 outputs.add(mOutputs.keyAt(i));
4296 }
4297 }
4298 }
4299 // Clear any profiles associated with the disconnected device.
4300 for (size_t i = 0; i < mHwModules.size(); i++)
4301 {
4302 if (mHwModules[i]->mHandle == 0) {
4303 continue;
4304 }
4305 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4306 {
4307 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
4308 if (profile->supportDevice(device)) {
4309 ALOGV("checkOutputsForDevice(): "
4310 "clearing direct output profile %zu on module %zu", j, i);
4311 profile->clearAudioProfiles();
4312 }
4313 }
4314 }
4315 }
4316 return NO_ERROR;
4317 }
4318
4319 status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
4320 audio_policy_dev_state_t state,
4321 SortedVector<audio_io_handle_t>& inputs,
4322 const String8& address)
4323 {
4324 audio_devices_t device = devDesc->type();
4325 sp<AudioInputDescriptor> desc;
4326
4327 if (audio_device_is_digital(device)) {
4328 // erase all current sample rates, formats and channel masks
4329 devDesc->clearAudioProfiles();
4330 }
4331
4332 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4333 // first list already open inputs that can be routed to this device
4334 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4335 desc = mInputs.valueAt(input_index);
4336 if (desc->mProfile->supportDevice(device)) {
4337 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4338 inputs.add(mInputs.keyAt(input_index));
4339 }
4340 }
4341
4342 // then look for input profiles that can be routed to this device
4343 SortedVector< sp<IOProfile> > profiles;
4344 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4345 {
4346 if (mHwModules[module_idx]->mHandle == 0) {
4347 continue;
4348 }
4349 for (size_t profile_index = 0;
4350 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4351 profile_index++)
4352 {
4353 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4354
4355 if (profile->supportDevice(device)) {
4356 if (!device_distinguishes_on_address(device) ||
4357 profile->supportDeviceAddress(address)) {
4358 profiles.add(profile);
4359 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4360 profile_index, module_idx);
4361 }
4362 }
4363 }
4364 }
4365
4366 if (profiles.isEmpty() && inputs.isEmpty()) {
4367 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4368 return BAD_VALUE;
4369 }
4370
4371 // open inputs for matching profiles if needed. Direct inputs are also opened to
4372 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4373 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4374
4375 sp<IOProfile> profile = profiles[profile_index];
4376 // nothing to do if one input is already opened for this profile
4377 size_t input_index;
4378 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4379 desc = mInputs.valueAt(input_index);
4380 if (desc->mProfile == profile) {
4381 if (audio_device_is_digital(device)) {
4382 devDesc->importAudioPort(profile);
4383 }
4384 break;
4385 }
4386 }
4387 if (input_index != mInputs.size()) {
4388 continue;
4389 }
4390
4391 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4392 desc = new AudioInputDescriptor(profile);
4393 desc->mDevice = device;
4394 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4395 config.sample_rate = desc->mSamplingRate;
4396 config.channel_mask = desc->mChannelMask;
4397 config.format = desc->mFormat;
4398 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
4399
4400 ALOGV("opening inputput for device %08x with params %s profile %p name %s",
4401 desc->mDevice, address.string(), profile.get(), profile->getName().string());
4402
4403 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
4404 &input,
4405 &config,
4406 &desc->mDevice,
4407 address,
4408 AUDIO_SOURCE_MIC,
4409 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
4410
4411 if (status == NO_ERROR) {
4412 desc->mSamplingRate = config.sample_rate;
4413 desc->mChannelMask = config.channel_mask;
4414 desc->mFormat = config.format;
4415
4416 if (!address.isEmpty()) {
4417 char *param = audio_device_address_to_parameter(device, address);
4418 mpClientInterface->setParameters(input, String8(param));
4419 free(param);
4420 }
4421 updateAudioProfiles(device, input, profile->getAudioProfiles());
4422 if (!profile->hasValidAudioProfile()) {
4423 ALOGW("checkInputsForDevice() direct input missing param");
4424 mpClientInterface->closeInput(input);
4425 input = AUDIO_IO_HANDLE_NONE;
4426 }
4427
4428 if (input != 0) {
4429 addInput(input, desc);
4430 }
4431 } // endif input != 0
4432
4433 if (input == AUDIO_IO_HANDLE_NONE) {
4434 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
4435 profiles.removeAt(profile_index);
4436 profile_index--;
4437 } else {
4438 inputs.add(input);
4439 if (audio_device_is_digital(device)) {
4440 devDesc->importAudioPort(profile);
4441 }
4442 ALOGV("checkInputsForDevice(): adding input %d", input);
4443 }
4444 } // end scan profiles
4445
4446 if (profiles.isEmpty()) {
4447 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4448 return BAD_VALUE;
4449 }
4450 } else {
4451 // Disconnect
4452 // check if one opened input is not needed any more after disconnecting one device
4453 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4454 desc = mInputs.valueAt(input_index);
4455 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
4456 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4457 mInputs.keyAt(input_index));
4458 inputs.add(mInputs.keyAt(input_index));
4459 }
4460 }
4461 // Clear any profiles associated with the disconnected device.
4462 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4463 if (mHwModules[module_index]->mHandle == 0) {
4464 continue;
4465 }
4466 for (size_t profile_index = 0;
4467 profile_index < mHwModules[module_index]->mInputProfiles.size();
4468 profile_index++) {
4469 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
4470 if (profile->supportDevice(device)) {
4471 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
4472 profile_index, module_index);
4473 profile->clearAudioProfiles();
4474 }
4475 }
4476 }
4477 } // end disconnect
4478
4479 return NO_ERROR;
4480 }
4481
4482
4483 void AudioPolicyManager::closeOutput(audio_io_handle_t output)
4484 {
4485 ALOGV("closeOutput(%d)", output);
4486
4487 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
4488 if (outputDesc == NULL) {
4489 ALOGW("closeOutput() unknown output %d", output);
4490 return;
4491 }
4492 mPolicyMixes.closeOutput(outputDesc);
4493
4494 // look for duplicated outputs connected to the output being removed.
4495 for (size_t i = 0; i < mOutputs.size(); i++) {
4496 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
4497 if (dupOutputDesc->isDuplicated() &&
4498 (dupOutputDesc->mOutput1 == outputDesc ||
4499 dupOutputDesc->mOutput2 == outputDesc)) {
4500 sp<AudioOutputDescriptor> outputDesc2;
4501 if (dupOutputDesc->mOutput1 == outputDesc) {
4502 outputDesc2 = dupOutputDesc->mOutput2;
4503 } else {
4504 outputDesc2 = dupOutputDesc->mOutput1;
4505 }
4506 // As all active tracks on duplicated output will be deleted,
4507 // and as they were also referenced on the other output, the reference
4508 // count for their stream type must be adjusted accordingly on
4509 // the other output.
4510 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
4511 int refCount = dupOutputDesc->mRefCount[j];
4512 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
4513 }
4514 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4515 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4516
4517 mpClientInterface->closeOutput(duplicatedOutput);
4518 removeOutput(duplicatedOutput);
4519 }
4520 }
4521
4522 nextAudioPortGeneration();
4523
4524 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
4525 if (index >= 0) {
4526 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4527 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4528 mAudioPatches.removeItemsAt(index);
4529 mpClientInterface->onAudioPatchListUpdate();
4530 }
4531
4532 AudioParameter param;
4533 param.add(String8("closing"), String8("true"));
4534 mpClientInterface->setParameters(output, param.toString());
4535
4536 mpClientInterface->closeOutput(output);
4537 removeOutput(output);
4538 mPreviousOutputs = mOutputs;
4539 }
4540
4541 void AudioPolicyManager::closeInput(audio_io_handle_t input)
4542 {
4543 ALOGV("closeInput(%d)", input);
4544
4545 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4546 if (inputDesc == NULL) {
4547 ALOGW("closeInput() unknown input %d", input);
4548 return;
4549 }
4550
4551 nextAudioPortGeneration();
4552
4553 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
4554 if (index >= 0) {
4555 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4556 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4557 mAudioPatches.removeItemsAt(index);
4558 mpClientInterface->onAudioPatchListUpdate();
4559 }
4560
4561 mpClientInterface->closeInput(input);
4562 mInputs.removeItem(input);
4563 }
4564
4565 SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4566 audio_devices_t device,
4567 const SwAudioOutputCollection& openOutputs)
4568 {
4569 SortedVector<audio_io_handle_t> outputs;
4570
4571 ALOGVV("getOutputsForDevice() device %04x", device);
4572 for (size_t i = 0; i < openOutputs.size(); i++) {
4573 ALOGVV("output %zu isDuplicated=%d device=%04x",
4574 i, openOutputs.valueAt(i)->isDuplicated(),
4575 openOutputs.valueAt(i)->supportedDevices());
4576 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4577 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4578 outputs.add(openOutputs.keyAt(i));
4579 }
4580 }
4581 return outputs;
4582 }
4583
4584 bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
4585 SortedVector<audio_io_handle_t>& outputs2)
4586 {
4587 if (outputs1.size() != outputs2.size()) {
4588 return false;
4589 }
4590 for (size_t i = 0; i < outputs1.size(); i++) {
4591 if (outputs1[i] != outputs2[i]) {
4592 return false;
4593 }
4594 }
4595 return true;
4596 }
4597
4598 void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
4599 {
4600 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4601 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4602 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4603 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4604
4605 // also take into account external policy-related changes: add all outputs which are
4606 // associated with policies in the "before" and "after" output vectors
4607 ALOGVV("checkOutputForStrategy(): policy related outputs");
4608 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
4609 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
4610 if (desc != 0 && desc->mPolicyMix != NULL) {
4611 srcOutputs.add(desc->mIoHandle);
4612 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4613 }
4614 }
4615 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
4616 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4617 if (desc != 0 && desc->mPolicyMix != NULL) {
4618 dstOutputs.add(desc->mIoHandle);
4619 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4620 }
4621 }
4622
4623 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4624 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4625 strategy, srcOutputs[0], dstOutputs[0]);
4626 // mute strategy while moving tracks from one output to another
4627 for (size_t i = 0; i < srcOutputs.size(); i++) {
4628 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
4629 if (isStrategyActive(desc, strategy)) {
4630 setStrategyMute(strategy, true, desc);
4631 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
4632 }
4633 sp<AudioSourceDescriptor> source =
4634 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4635 if (source != 0){
4636 connectAudioSource(source);
4637 }
4638 }
4639
4640 // Move effects associated to this strategy from previous output to new output
4641 if (strategy == STRATEGY_MEDIA) {
4642 selectOutputForMusicEffects();
4643 }
4644 // Move tracks associated to this strategy from previous output to new output
4645 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
4646 if (getStrategy((audio_stream_type_t)i) == strategy) {
4647 mpClientInterface->invalidateStream((audio_stream_type_t)i);
4648 }
4649 }
4650 }
4651 }
4652
4653 void AudioPolicyManager::checkOutputForAllStrategies()
4654 {
4655 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4656 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
4657 checkOutputForStrategy(STRATEGY_PHONE);
4658 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4659 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
4660 checkOutputForStrategy(STRATEGY_SONIFICATION);
4661 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4662 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
4663 checkOutputForStrategy(STRATEGY_MEDIA);
4664 checkOutputForStrategy(STRATEGY_DTMF);
4665 checkOutputForStrategy(STRATEGY_REROUTING);
4666 }
4667
4668 void AudioPolicyManager::checkA2dpSuspend()
4669 {
4670 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
4671 if (a2dpOutput == 0) {
4672 mA2dpSuspended = false;
4673 return;
4674 }
4675
4676 bool isScoConnected =
4677 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4678 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4679 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
4680
4681 // if suspended, restore A2DP output if:
4682 // ((SCO device is NOT connected) ||
4683 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4684 // (phone state is NOT in call) && (phone state is NOT ringing)))
4685 //
4686 // if not suspended, suspend A2DP output if:
4687 // (SCO device is connected) &&
4688 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4689 // ((phone state is in call) || (phone state is ringing)))
4690 //
4691 if (mA2dpSuspended) {
4692 if (!isScoConnected ||
4693 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4694 AUDIO_POLICY_FORCE_BT_SCO) &&
4695 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4696 AUDIO_POLICY_FORCE_BT_SCO) &&
4697 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
4698 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
4699
4700 mpClientInterface->restoreOutput(a2dpOutput);
4701 mA2dpSuspended = false;
4702 }
4703 } else {
4704 if (isScoConnected &&
4705 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4706 AUDIO_POLICY_FORCE_BT_SCO) ||
4707 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4708 AUDIO_POLICY_FORCE_BT_SCO) ||
4709 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
4710 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
4711
4712 mpClientInterface->suspendOutput(a2dpOutput);
4713 mA2dpSuspended = true;
4714 }
4715 }
4716 }
4717
4718 audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4719 bool fromCache)
4720 {
4721 audio_devices_t device = AUDIO_DEVICE_NONE;
4722
4723 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
4724 if (index >= 0) {
4725 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4726 if (patchDesc->mUid != mUidCached) {
4727 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4728 outputDesc->device(), outputDesc->getPatchHandle());
4729 return outputDesc->device();
4730 }
4731 }
4732
4733 // check the following by order of priority to request a routing change if necessary:
4734 // 1: the strategy enforced audible is active and enforced on the output:
4735 // use device for strategy enforced audible
4736 // 2: we are in call or the strategy phone is active on the output:
4737 // use device for strategy phone
4738 // 3: the strategy sonification is active on the output:
4739 // use device for strategy sonification
4740 // 4: the strategy for enforced audible is active but not enforced on the output:
4741 // use the device for strategy enforced audible
4742 // 5: the strategy accessibility is active on the output:
4743 // use device for strategy accessibility
4744 // 6: the strategy "respectful" sonification is active on the output:
4745 // use device for strategy "respectful" sonification
4746 // 7: the strategy media is active on the output:
4747 // use device for strategy media
4748 // 8: the strategy DTMF is active on the output:
4749 // use device for strategy DTMF
4750 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
4751 // use device for strategy t-t-s
4752 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
4753 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
4754 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4755 } else if (isInCall() ||
4756 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
4757 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
4758 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
4759 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
4760 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4761 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4762 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4763 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
4764 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
4765 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
4766 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
4767 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
4768 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
4769 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
4770 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
4771 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
4772 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
4773 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
4774 }
4775
4776 ALOGV("getNewOutputDevice() selected device %x", device);
4777 return device;
4778 }
4779
4780 audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
4781 {
4782 audio_devices_t device = AUDIO_DEVICE_NONE;
4783
4784 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
4785 if (index >= 0) {
4786 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4787 if (patchDesc->mUid != mUidCached) {
4788 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4789 inputDesc->mDevice, inputDesc->getPatchHandle());
4790 return inputDesc->mDevice;
4791 }
4792 }
4793
4794 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4795 if (isInCall()) {
4796 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4797 } else if (source != AUDIO_SOURCE_DEFAULT) {
4798 device = getDeviceAndMixForInputSource(source);
4799 }
4800
4801 return device;
4802 }
4803
4804 bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4805 audio_stream_type_t stream2) {
4806 return (stream1 == stream2);
4807 }
4808
4809 uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
4810 return (uint32_t)getStrategy(stream);
4811 }
4812
4813 audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
4814 // By checking the range of stream before calling getStrategy, we avoid
4815 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4816 // and then return STRATEGY_MEDIA, but we want to return the empty set.
4817 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
4818 return AUDIO_DEVICE_NONE;
4819 }
4820 audio_devices_t devices = AUDIO_DEVICE_NONE;
4821 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4822 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
4823 continue;
4824 }
4825 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
4826 audio_devices_t curDevices =
4827 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
4828 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4829 for (size_t i = 0; i < outputs.size(); i++) {
4830 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
4831 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
4832 curDevices |= outputDesc->device();
4833 }
4834 }
4835 devices |= curDevices;
4836 }
4837
4838 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4839 and doesn't really need to.*/
4840 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4841 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4842 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4843 }
4844 return devices;
4845 }
4846
4847 routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4848 {
4849 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4850 return mEngine->getStrategyForStream(stream);
4851 }
4852
4853 uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4854 // flags to strategy mapping
4855 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4856 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4857 }
4858 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4859 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4860 }
4861 // usage to strategy mapping
4862 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
4863 }
4864
4865 void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
4866 switch(stream) {
4867 case AUDIO_STREAM_MUSIC:
4868 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4869 updateDevicesAndOutputs();
4870 break;
4871 default:
4872 break;
4873 }
4874 }
4875
4876 uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4877
4878 // skip beacon mute management if a dedicated TTS output is available
4879 if (mTtsOutputAvailable) {
4880 return 0;
4881 }
4882
4883 switch(event) {
4884 case STARTING_OUTPUT:
4885 mBeaconMuteRefCount++;
4886 break;
4887 case STOPPING_OUTPUT:
4888 if (mBeaconMuteRefCount > 0) {
4889 mBeaconMuteRefCount--;
4890 }
4891 break;
4892 case STARTING_BEACON:
4893 mBeaconPlayingRefCount++;
4894 break;
4895 case STOPPING_BEACON:
4896 if (mBeaconPlayingRefCount > 0) {
4897 mBeaconPlayingRefCount--;
4898 }
4899 break;
4900 }
4901
4902 if (mBeaconMuteRefCount > 0) {
4903 // any playback causes beacon to be muted
4904 return setBeaconMute(true);
4905 } else {
4906 // no other playback: unmute when beacon starts playing, mute when it stops
4907 return setBeaconMute(mBeaconPlayingRefCount == 0);
4908 }
4909 }
4910
4911 uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4912 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4913 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4914 // keep track of muted state to avoid repeating mute/unmute operations
4915 if (mBeaconMuted != mute) {
4916 // mute/unmute AUDIO_STREAM_TTS on all outputs
4917 ALOGV("\t muting %d", mute);
4918 uint32_t maxLatency = 0;
4919 for (size_t i = 0; i < mOutputs.size(); i++) {
4920 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4921 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4922 desc,
4923 0 /*delay*/, AUDIO_DEVICE_NONE);
4924 const uint32_t latency = desc->latency() * 2;
4925 if (latency > maxLatency) {
4926 maxLatency = latency;
4927 }
4928 }
4929 mBeaconMuted = mute;
4930 return maxLatency;
4931 }
4932 return 0;
4933 }
4934
4935 audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
4936 bool fromCache)
4937 {
4938 // Routing
4939 // see if we have an explicit route
4940 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4941 // (getStrategy(stream)).
4942 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4943 // and activity count is non-zero and the device in the route descriptor is available
4944 // then select this device.
4945 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4946 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
4947 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4948 if ((routeStrategy == strategy) && route->isActive() &&
4949 (mAvailableOutputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
4950 return route->mDeviceDescriptor->type();
4951 }
4952 }
4953
4954 if (fromCache) {
4955 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4956 strategy, mDeviceForStrategy[strategy]);
4957 return mDeviceForStrategy[strategy];
4958 }
4959 return mEngine->getDeviceForStrategy(strategy);
4960 }
4961
4962 void AudioPolicyManager::updateDevicesAndOutputs()
4963 {
4964 for (int i = 0; i < NUM_STRATEGIES; i++) {
4965 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4966 }
4967 mPreviousOutputs = mOutputs;
4968 }
4969
4970 uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
4971 audio_devices_t prevDevice,
4972 uint32_t delayMs)
4973 {
4974 // mute/unmute strategies using an incompatible device combination
4975 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4976 // if unmuting, unmute only after the specified delay
4977 if (outputDesc->isDuplicated()) {
4978 return 0;
4979 }
4980
4981 uint32_t muteWaitMs = 0;
4982 audio_devices_t device = outputDesc->device();
4983 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
4984
4985 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4986 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4987 curDevice = curDevice & outputDesc->supportedDevices();
4988 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4989 bool doMute = false;
4990
4991 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4992 doMute = true;
4993 outputDesc->mStrategyMutedByDevice[i] = true;
4994 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4995 doMute = true;
4996 outputDesc->mStrategyMutedByDevice[i] = false;
4997 }
4998 if (doMute) {
4999 for (size_t j = 0; j < mOutputs.size(); j++) {
5000 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
5001 // skip output if it does not share any device with current output
5002 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5003 == AUDIO_DEVICE_NONE) {
5004 continue;
5005 }
5006 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
5007 mute ? "muting" : "unmuting", i, curDevice);
5008 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
5009 if (isStrategyActive(desc, (routing_strategy)i)) {
5010 if (mute) {
5011 // FIXME: should not need to double latency if volume could be applied
5012 // immediately by the audioflinger mixer. We must account for the delay
5013 // between now and the next time the audioflinger thread for this output
5014 // will process a buffer (which corresponds to one buffer size,
5015 // usually 1/2 or 1/4 of the latency).
5016 if (muteWaitMs < desc->latency() * 2) {
5017 muteWaitMs = desc->latency() * 2;
5018 }
5019 }
5020 }
5021 }
5022 }
5023 }
5024
5025 // temporary mute output if device selection changes to avoid volume bursts due to
5026 // different per device volumes
5027 if (outputDesc->isActive() && (device != prevDevice)) {
5028 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5029 // temporary mute duration is conservatively set to 4 times the reported latency
5030 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5031 if (muteWaitMs < tempMuteWaitMs) {
5032 muteWaitMs = tempMuteWaitMs;
5033 }
5034
5035 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5036 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
5037 // make sure that we do not start the temporary mute period too early in case of
5038 // delayed device change
5039 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
5040 setStrategyMute((routing_strategy)i, false, outputDesc,
5041 delayMs + tempMuteDurationMs, device);
5042 }
5043 }
5044 }
5045
5046 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5047 if (muteWaitMs > delayMs) {
5048 muteWaitMs -= delayMs;
5049 usleep(muteWaitMs * 1000);
5050 return muteWaitMs;
5051 }
5052 return 0;
5053 }
5054
5055 uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
5056 audio_devices_t device,
5057 bool force,
5058 int delayMs,
5059 audio_patch_handle_t *patchHandle,
5060 const char* address)
5061 {
5062 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
5063 AudioParameter param;
5064 uint32_t muteWaitMs;
5065
5066 if (outputDesc->isDuplicated()) {
5067 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
5068 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
5069 return muteWaitMs;
5070 }
5071 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5072 // output profile
5073 if ((device != AUDIO_DEVICE_NONE) &&
5074 ((device & outputDesc->supportedDevices()) == 0)) {
5075 return 0;
5076 }
5077
5078 // filter devices according to output selected
5079 device = (audio_devices_t)(device & outputDesc->supportedDevices());
5080
5081 audio_devices_t prevDevice = outputDesc->mDevice;
5082
5083 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
5084
5085 if (device != AUDIO_DEVICE_NONE) {
5086 outputDesc->mDevice = device;
5087 }
5088 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5089
5090 // Do not change the routing if:
5091 // the requested device is AUDIO_DEVICE_NONE
5092 // OR the requested device is the same as current device
5093 // AND force is not specified
5094 // AND the output is connected by a valid audio patch.
5095 // Doing this check here allows the caller to call setOutputDevice() without conditions
5096 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5097 !force &&
5098 outputDesc->getPatchHandle() != 0) {
5099 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
5100 return muteWaitMs;
5101 }
5102
5103 ALOGV("setOutputDevice() changing device");
5104
5105 // do the routing
5106 if (device == AUDIO_DEVICE_NONE) {
5107 resetOutputDevice(outputDesc, delayMs, NULL);
5108 } else {
5109 DeviceVector deviceList;
5110 if ((address == NULL) || (strlen(address) == 0)) {
5111 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
5112 } else {
5113 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
5114 }
5115
5116 if (!deviceList.isEmpty()) {
5117 struct audio_patch patch;
5118 outputDesc->toAudioPortConfig(&patch.sources[0]);
5119 patch.num_sources = 1;
5120 patch.num_sinks = 0;
5121 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
5122 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
5123 patch.num_sinks++;
5124 }
5125 ssize_t index;
5126 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5127 index = mAudioPatches.indexOfKey(*patchHandle);
5128 } else {
5129 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
5130 }
5131 sp< AudioPatch> patchDesc;
5132 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5133 if (index >= 0) {
5134 patchDesc = mAudioPatches.valueAt(index);
5135 afPatchHandle = patchDesc->mAfPatchHandle;
5136 }
5137
5138 status_t status = mpClientInterface->createAudioPatch(&patch,
5139 &afPatchHandle,
5140 delayMs);
5141 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
5142 "num_sources %d num_sinks %d",
5143 status, afPatchHandle, patch.num_sources, patch.num_sinks);
5144 if (status == NO_ERROR) {
5145 if (index < 0) {
5146 patchDesc = new AudioPatch(&patch, mUidCached);
5147 addAudioPatch(patchDesc->mHandle, patchDesc);
5148 } else {
5149 patchDesc->mPatch = patch;
5150 }
5151 patchDesc->mAfPatchHandle = afPatchHandle;
5152 if (patchHandle) {
5153 *patchHandle = patchDesc->mHandle;
5154 }
5155 outputDesc->setPatchHandle(patchDesc->mHandle);
5156 nextAudioPortGeneration();
5157 mpClientInterface->onAudioPatchListUpdate();
5158 }
5159 }
5160
5161 // inform all input as well
5162 for (size_t i = 0; i < mInputs.size(); i++) {
5163 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
5164 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
5165 AudioParameter inputCmd = AudioParameter();
5166 ALOGV("%s: inform input %d of device:%d", __func__,
5167 inputDescriptor->mIoHandle, device);
5168 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5169 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5170 inputCmd.toString(),
5171 delayMs);
5172 }
5173 }
5174 }
5175
5176 // update stream volumes according to new device
5177 applyStreamVolumes(outputDesc, device, delayMs);
5178
5179 return muteWaitMs;
5180 }
5181
5182 status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
5183 int delayMs,
5184 audio_patch_handle_t *patchHandle)
5185 {
5186 ssize_t index;
5187 if (patchHandle) {
5188 index = mAudioPatches.indexOfKey(*patchHandle);
5189 } else {
5190 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
5191 }
5192 if (index < 0) {
5193 return INVALID_OPERATION;
5194 }
5195 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5196 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
5197 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
5198 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
5199 removeAudioPatch(patchDesc->mHandle);
5200 nextAudioPortGeneration();
5201 mpClientInterface->onAudioPatchListUpdate();
5202 return status;
5203 }
5204
5205 status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5206 audio_devices_t device,
5207 bool force,
5208 audio_patch_handle_t *patchHandle)
5209 {
5210 status_t status = NO_ERROR;
5211
5212 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5213 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5214 inputDesc->mDevice = device;
5215
5216 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5217 if (!deviceList.isEmpty()) {
5218 struct audio_patch patch;
5219 inputDesc->toAudioPortConfig(&patch.sinks[0]);
5220 // AUDIO_SOURCE_HOTWORD is for internal use only:
5221 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
5222 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
5223 !inputDesc->isSoundTrigger()) {
5224 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5225 }
5226 patch.num_sinks = 1;
5227 //only one input device for now
5228 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
5229 patch.num_sources = 1;
5230 ssize_t index;
5231 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5232 index = mAudioPatches.indexOfKey(*patchHandle);
5233 } else {
5234 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
5235 }
5236 sp< AudioPatch> patchDesc;
5237 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5238 if (index >= 0) {
5239 patchDesc = mAudioPatches.valueAt(index);
5240 afPatchHandle = patchDesc->mAfPatchHandle;
5241 }
5242
5243 status_t status = mpClientInterface->createAudioPatch(&patch,
5244 &afPatchHandle,
5245 0);
5246 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
5247 status, afPatchHandle);
5248 if (status == NO_ERROR) {
5249 if (index < 0) {
5250 patchDesc = new AudioPatch(&patch, mUidCached);
5251 addAudioPatch(patchDesc->mHandle, patchDesc);
5252 } else {
5253 patchDesc->mPatch = patch;
5254 }
5255 patchDesc->mAfPatchHandle = afPatchHandle;
5256 if (patchHandle) {
5257 *patchHandle = patchDesc->mHandle;
5258 }
5259 inputDesc->setPatchHandle(patchDesc->mHandle);
5260 nextAudioPortGeneration();
5261 mpClientInterface->onAudioPatchListUpdate();
5262 }
5263 }
5264 }
5265 return status;
5266 }
5267
5268 status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5269 audio_patch_handle_t *patchHandle)
5270 {
5271 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5272 ssize_t index;
5273 if (patchHandle) {
5274 index = mAudioPatches.indexOfKey(*patchHandle);
5275 } else {
5276 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
5277 }
5278 if (index < 0) {
5279 return INVALID_OPERATION;
5280 }
5281 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5282 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
5283 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
5284 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
5285 removeAudioPatch(patchDesc->mHandle);
5286 nextAudioPortGeneration();
5287 mpClientInterface->onAudioPatchListUpdate();
5288 return status;
5289 }
5290
5291 sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
5292 const String8& address,
5293 uint32_t& samplingRate,
5294 audio_format_t& format,
5295 audio_channel_mask_t& channelMask,
5296 audio_input_flags_t flags)
5297 {
5298 // Choose an input profile based on the requested capture parameters: select the first available
5299 // profile supporting all requested parameters.
5300 //
5301 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5302 // the best matching profile, not the first one.
5303
5304 for (size_t i = 0; i < mHwModules.size(); i++)
5305 {
5306 if (mHwModules[i]->mHandle == 0) {
5307 continue;
5308 }
5309 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5310 {
5311 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
5312 // profile->log();
5313 if (profile->isCompatibleProfile(device, address, samplingRate,
5314 &samplingRate /*updatedSamplingRate*/,
5315 format,
5316 &format /*updatedFormat*/,
5317 channelMask,
5318 &channelMask /*updatedChannelMask*/,
5319 (audio_output_flags_t) flags)) {
5320
5321 return profile;
5322 }
5323 }
5324 }
5325 return NULL;
5326 }
5327
5328
5329 audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
5330 sp<AudioPolicyMix> *policyMix)
5331 {
5332 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5333 audio_devices_t selectedDeviceFromMix =
5334 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
5335
5336 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5337 return selectedDeviceFromMix;
5338 }
5339 return getDeviceForInputSource(inputSource);
5340 }
5341
5342 audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5343 {
5344 // Routing
5345 // Scan the whole RouteMap to see if we have an explicit route:
5346 // if the input source in the RouteMap is the same as the argument above,
5347 // and activity count is non-zero and the device in the route descriptor is available
5348 // then select this device.
5349 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5350 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
5351 if ((inputSource == route->mSource) && route->isActive() &&
5352 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
5353 return route->mDeviceDescriptor->type();
5354 }
5355 }
5356
5357 return mEngine->getDeviceForInputSource(inputSource);
5358 }
5359
5360 float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
5361 int index,
5362 audio_devices_t device)
5363 {
5364 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
5365
5366 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5367 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5368 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5369 // the ringtone volume
5370 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5371 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5372 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5373 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5374 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5375 }
5376
5377 // in-call: always cap earpiece volume by voice volume + some low headroom
5378 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) && isInCall()) {
5379 switch (stream) {
5380 case AUDIO_STREAM_SYSTEM:
5381 case AUDIO_STREAM_RING:
5382 case AUDIO_STREAM_MUSIC:
5383 case AUDIO_STREAM_ALARM:
5384 case AUDIO_STREAM_NOTIFICATION:
5385 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5386 case AUDIO_STREAM_DTMF:
5387 case AUDIO_STREAM_ACCESSIBILITY: {
5388 const float maxVoiceVolDb = computeVolume(AUDIO_STREAM_VOICE_CALL, index, device)
5389 + IN_CALL_EARPIECE_HEADROOM_DB;
5390 if (volumeDB > maxVoiceVolDb) {
5391 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5392 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5393 volumeDB = maxVoiceVolDb;
5394 }
5395 } break;
5396 default:
5397 break;
5398 }
5399 }
5400
5401 // if a headset is connected, apply the following rules to ring tones and notifications
5402 // to avoid sound level bursts in user's ears:
5403 // - always attenuate notifications volume by 6dB
5404 // - attenuate ring tones volume by 6dB unless music is not playing and
5405 // speaker is part of the select devices
5406 // - if music is playing, always limit the volume to current music volume,
5407 // with a minimum threshold at -36dB so that notification is always perceived.
5408 const routing_strategy stream_strategy = getStrategy(stream);
5409 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5410 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5411 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5412 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
5413 AUDIO_DEVICE_OUT_USB_HEADSET)) &&
5414 ((stream_strategy == STRATEGY_SONIFICATION)
5415 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
5416 || (stream == AUDIO_STREAM_SYSTEM)
5417 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
5418 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
5419 mVolumeCurves->canBeMuted(stream)) {
5420 // when the phone is ringing we must consider that music could have been paused just before
5421 // by the music application and behave as if music was active if the last music track was
5422 // just stopped
5423 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
5424 mLimitRingtoneVolume) {
5425 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
5426 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
5427 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
5428 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5429 musicDevice),
5430 musicDevice);
5431 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5432 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
5433 if (volumeDB > minVolDB) {
5434 volumeDB = minVolDB;
5435 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
5436 }
5437 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5438 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5439 // on A2DP, also ensure notification volume is not too low compared to media when
5440 // intended to be played
5441 if ((volumeDB > -96.0f) &&
5442 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5443 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5444 stream, device,
5445 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5446 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5447 }
5448 }
5449 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5450 stream_strategy != STRATEGY_SONIFICATION) {
5451 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
5452 }
5453 }
5454
5455 return volumeDB;
5456 }
5457
5458 status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
5459 int index,
5460 const sp<AudioOutputDescriptor>& outputDesc,
5461 audio_devices_t device,
5462 int delayMs,
5463 bool force)
5464 {
5465 // do not change actual stream volume if the stream is muted
5466 if (outputDesc->mMuteCount[stream] != 0) {
5467 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5468 stream, outputDesc->mMuteCount[stream]);
5469 return NO_ERROR;
5470 }
5471 audio_policy_forced_cfg_t forceUseForComm =
5472 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
5473 // do not change in call volume if bluetooth is connected and vice versa
5474 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5475 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
5476 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
5477 stream, forceUseForComm);
5478 return INVALID_OPERATION;
5479 }
5480
5481 if (device == AUDIO_DEVICE_NONE) {
5482 device = outputDesc->device();
5483 }
5484
5485 float volumeDb = computeVolume(stream, index, device);
5486 if (outputDesc->isFixedVolume(device)) {
5487 volumeDb = 0.0f;
5488 }
5489
5490 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
5491
5492 if (stream == AUDIO_STREAM_VOICE_CALL ||
5493 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5494 float voiceVolume;
5495 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
5496 if (stream == AUDIO_STREAM_VOICE_CALL) {
5497 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
5498 } else {
5499 voiceVolume = 1.0;
5500 }
5501
5502 if (voiceVolume != mLastVoiceVolume) {
5503 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5504 mLastVoiceVolume = voiceVolume;
5505 }
5506 }
5507
5508 return NO_ERROR;
5509 }
5510
5511 void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5512 audio_devices_t device,
5513 int delayMs,
5514 bool force)
5515 {
5516 ALOGVV("applyStreamVolumes() for device %08x", device);
5517
5518 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5519 checkAndSetVolume((audio_stream_type_t)stream,
5520 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
5521 outputDesc,
5522 device,
5523 delayMs,
5524 force);
5525 }
5526 }
5527
5528 void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
5529 bool on,
5530 const sp<AudioOutputDescriptor>& outputDesc,
5531 int delayMs,
5532 audio_devices_t device)
5533 {
5534 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5535 strategy, on, outputDesc->getId());
5536 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5537 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5538 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
5539 }
5540 }
5541 }
5542
5543 void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
5544 bool on,
5545 const sp<AudioOutputDescriptor>& outputDesc,
5546 int delayMs,
5547 audio_devices_t device)
5548 {
5549 if (device == AUDIO_DEVICE_NONE) {
5550 device = outputDesc->device();
5551 }
5552
5553 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5554 stream, on, outputDesc->mMuteCount[stream], device);
5555
5556 if (on) {
5557 if (outputDesc->mMuteCount[stream] == 0) {
5558 if (mVolumeCurves->canBeMuted(stream) &&
5559 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5560 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
5561 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
5562 }
5563 }
5564 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5565 outputDesc->mMuteCount[stream]++;
5566 } else {
5567 if (outputDesc->mMuteCount[stream] == 0) {
5568 ALOGV("setStreamMute() unmuting non muted stream!");
5569 return;
5570 }
5571 if (--outputDesc->mMuteCount[stream] == 0) {
5572 checkAndSetVolume(stream,
5573 mVolumeCurves->getVolumeIndex(stream, device),
5574 outputDesc,
5575 device,
5576 delayMs);
5577 }
5578 }
5579 }
5580
5581 void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
5582 bool starting, bool stateChange)
5583 {
5584 if(!hasPrimaryOutput()) {
5585 return;
5586 }
5587
5588 // if the stream pertains to sonification strategy and we are in call we must
5589 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5590 // in the device used for phone strategy and play the tone if the selected device does not
5591 // interfere with the device used for phone strategy
5592 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5593 // many times as there are active tracks on the output
5594 const routing_strategy stream_strategy = getStrategy(stream);
5595 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5596 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
5597 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
5598 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5599 stream, starting, outputDesc->mDevice, stateChange);
5600 if (outputDesc->mRefCount[stream]) {
5601 int muteCount = 1;
5602 if (stateChange) {
5603 muteCount = outputDesc->mRefCount[stream];
5604 }
5605 if (audio_is_low_visibility(stream)) {
5606 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5607 for (int i = 0; i < muteCount; i++) {
5608 setStreamMute(stream, starting, mPrimaryOutput);
5609 }
5610 } else {
5611 ALOGV("handleIncallSonification() high visibility");
5612 if (outputDesc->device() &
5613 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5614 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5615 for (int i = 0; i < muteCount; i++) {
5616 setStreamMute(stream, starting, mPrimaryOutput);
5617 }
5618 }
5619 if (starting) {
5620 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5621 AUDIO_STREAM_VOICE_CALL);
5622 } else {
5623 mpClientInterface->stopTone();
5624 }
5625 }
5626 }
5627 }
5628 }
5629
5630 audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5631 {
5632 // flags to stream type mapping
5633 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5634 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5635 }
5636 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5637 return AUDIO_STREAM_BLUETOOTH_SCO;
5638 }
5639 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5640 return AUDIO_STREAM_TTS;
5641 }
5642
5643 // usage to stream type mapping
5644 switch (attr->usage) {
5645 case AUDIO_USAGE_MEDIA:
5646 case AUDIO_USAGE_GAME:
5647 case AUDIO_USAGE_ASSISTANT:
5648 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5649 return AUDIO_STREAM_MUSIC;
5650 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5651 return AUDIO_STREAM_ACCESSIBILITY;
5652 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5653 return AUDIO_STREAM_SYSTEM;
5654 case AUDIO_USAGE_VOICE_COMMUNICATION:
5655 return AUDIO_STREAM_VOICE_CALL;
5656
5657 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5658 return AUDIO_STREAM_DTMF;
5659
5660 case AUDIO_USAGE_ALARM:
5661 return AUDIO_STREAM_ALARM;
5662 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5663 return AUDIO_STREAM_RING;
5664
5665 case AUDIO_USAGE_NOTIFICATION:
5666 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5667 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5668 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5669 case AUDIO_USAGE_NOTIFICATION_EVENT:
5670 return AUDIO_STREAM_NOTIFICATION;
5671
5672 case AUDIO_USAGE_UNKNOWN:
5673 default:
5674 return AUDIO_STREAM_MUSIC;
5675 }
5676 }
5677
5678 bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5679 {
5680 // has flags that map to a strategy?
5681 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5682 return true;
5683 }
5684
5685 // has known usage?
5686 switch (paa->usage) {
5687 case AUDIO_USAGE_UNKNOWN:
5688 case AUDIO_USAGE_MEDIA:
5689 case AUDIO_USAGE_VOICE_COMMUNICATION:
5690 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5691 case AUDIO_USAGE_ALARM:
5692 case AUDIO_USAGE_NOTIFICATION:
5693 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5694 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5695 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5696 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5697 case AUDIO_USAGE_NOTIFICATION_EVENT:
5698 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5699 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5700 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5701 case AUDIO_USAGE_GAME:
5702 case AUDIO_USAGE_VIRTUAL_SOURCE:
5703 case AUDIO_USAGE_ASSISTANT:
5704 break;
5705 default:
5706 return false;
5707 }
5708 return true;
5709 }
5710
5711 bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
5712 routing_strategy strategy, uint32_t inPastMs,
5713 nsecs_t sysTime) const
5714 {
5715 if ((sysTime == 0) && (inPastMs != 0)) {
5716 sysTime = systemTime();
5717 }
5718 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
5719 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5720 (NUM_STRATEGIES == strategy)) &&
5721 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5722 return true;
5723 }
5724 }
5725 return false;
5726 }
5727
5728 audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5729 {
5730 return mEngine->getForceUse(usage);
5731 }
5732
5733 bool AudioPolicyManager::isInCall()
5734 {
5735 return isStateInCall(mEngine->getPhoneState());
5736 }
5737
5738 bool AudioPolicyManager::isStateInCall(int state)
5739 {
5740 return is_state_in_call(state);
5741 }
5742
5743 void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5744 {
5745 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5746 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5747 if (sourceDesc->mDevice->equals(deviceDesc)) {
5748 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5749 stopAudioSource(sourceDesc->getHandle());
5750 }
5751 }
5752
5753 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5754 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5755 bool release = false;
5756 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5757 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5758 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5759 source->ext.device.type == deviceDesc->type()) {
5760 release = true;
5761 }
5762 }
5763 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5764 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5765 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5766 sink->ext.device.type == deviceDesc->type()) {
5767 release = true;
5768 }
5769 }
5770 if (release) {
5771 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5772 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5773 }
5774 }
5775 }
5776
5777 // Modify the list of surround sound formats supported.
5778 void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5779 FormatVector &formats = *formatsPtr;
5780 // TODO Set this based on Config properties.
5781 const bool alwaysForceAC3 = true;
5782
5783 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5784 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5785 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
5786
5787 // Analyze original support for various formats.
5788 bool supportsAC3 = false;
5789 bool supportsOtherSurround = false;
5790 bool supportsIEC61937 = false;
5791 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5792 audio_format_t format = formats[formatIndex];
5793 switch (format) {
5794 case AUDIO_FORMAT_AC3:
5795 supportsAC3 = true;
5796 break;
5797 case AUDIO_FORMAT_E_AC3:
5798 case AUDIO_FORMAT_DTS:
5799 case AUDIO_FORMAT_DTS_HD:
5800 supportsOtherSurround = true;
5801 break;
5802 case AUDIO_FORMAT_IEC61937:
5803 supportsIEC61937 = true;
5804 break;
5805 default:
5806 break;
5807 }
5808 }
5809
5810 // Modify formats based on surround preferences.
5811 // If NEVER, remove support for surround formats.
5812 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5813 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5814 // Remove surround sound related formats.
5815 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5816 audio_format_t format = formats[formatIndex];
5817 switch(format) {
5818 case AUDIO_FORMAT_AC3:
5819 case AUDIO_FORMAT_E_AC3:
5820 case AUDIO_FORMAT_DTS:
5821 case AUDIO_FORMAT_DTS_HD:
5822 case AUDIO_FORMAT_IEC61937:
5823 formats.removeAt(formatIndex);
5824 break;
5825 default:
5826 formatIndex++; // keep it
5827 break;
5828 }
5829 }
5830 supportsAC3 = false;
5831 supportsOtherSurround = false;
5832 supportsIEC61937 = false;
5833 }
5834 } else { // AUTO or ALWAYS
5835 // Most TVs support AC3 even if they do not report it in the EDID.
5836 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5837 && !supportsAC3) {
5838 formats.add(AUDIO_FORMAT_AC3);
5839 supportsAC3 = true;
5840 }
5841
5842 // If ALWAYS, add support for raw surround formats if all are missing.
5843 // This assumes that if any of these formats are reported by the HAL
5844 // then the report is valid and should not be modified.
5845 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5846 && !supportsOtherSurround) {
5847 formats.add(AUDIO_FORMAT_E_AC3);
5848 formats.add(AUDIO_FORMAT_DTS);
5849 formats.add(AUDIO_FORMAT_DTS_HD);
5850 supportsOtherSurround = true;
5851 }
5852
5853 // Add support for IEC61937 if any raw surround supported.
5854 // The HAL could do this but add it here, just in case.
5855 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5856 formats.add(AUDIO_FORMAT_IEC61937);
5857 supportsIEC61937 = true;
5858 }
5859 }
5860 }
5861
5862 // Modify the list of channel masks supported.
5863 void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5864 ChannelsVector &channelMasks = *channelMasksPtr;
5865 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5866 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5867
5868 // If NEVER, then remove support for channelMasks > stereo.
5869 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5870 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5871 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5872 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5873 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5874 channelMasks.removeAt(maskIndex);
5875 } else {
5876 maskIndex++;
5877 }
5878 }
5879 // If ALWAYS, then make sure we at least support 5.1
5880 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5881 bool supports5dot1 = false;
5882 // Are there any channel masks that can be considered "surround"?
5883 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5884 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5885 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5886 supports5dot1 = true;
5887 break;
5888 }
5889 }
5890 // If not then add 5.1 support.
5891 if (!supports5dot1) {
5892 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5893 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5894 }
5895 }
5896 }
5897
5898 void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5899 audio_io_handle_t ioHandle,
5900 AudioProfileVector &profiles)
5901 {
5902 String8 reply;
5903
5904 // Format MUST be checked first to update the list of AudioProfile
5905 if (profiles.hasDynamicFormat()) {
5906 reply = mpClientInterface->getParameters(
5907 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
5908 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
5909 AudioParameter repliedParameters(reply);
5910 if (repliedParameters.get(
5911 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
5912 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5913 return;
5914 }
5915 FormatVector formats = formatsFromString(reply.string());
5916 if (device == AUDIO_DEVICE_OUT_HDMI) {
5917 filterSurroundFormats(&formats);
5918 }
5919 profiles.setFormats(formats);
5920 }
5921 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5922
5923 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
5924 audio_format_t format = supportedFormats[formatIndex];
5925 ChannelsVector channelMasks;
5926 SampleRateVector samplingRates;
5927 AudioParameter requestedParameters;
5928 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
5929
5930 if (profiles.hasDynamicRateFor(format)) {
5931 reply = mpClientInterface->getParameters(
5932 ioHandle,
5933 requestedParameters.toString() + ";" +
5934 AudioParameter::keyStreamSupportedSamplingRates);
5935 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
5936 AudioParameter repliedParameters(reply);
5937 if (repliedParameters.get(
5938 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
5939 samplingRates = samplingRatesFromString(reply.string());
5940 }
5941 }
5942 if (profiles.hasDynamicChannelsFor(format)) {
5943 reply = mpClientInterface->getParameters(ioHandle,
5944 requestedParameters.toString() + ";" +
5945 AudioParameter::keyStreamSupportedChannels);
5946 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
5947 AudioParameter repliedParameters(reply);
5948 if (repliedParameters.get(
5949 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
5950 channelMasks = channelMasksFromString(reply.string());
5951 if (device == AUDIO_DEVICE_OUT_HDMI) {
5952 filterSurroundChannelMasks(&channelMasks);
5953 }
5954 }
5955 }
5956 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
5957 }
5958 }
5959
5960 }; // namespace android
5961