1 /*
2  * Copyright (C) 2015 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::AudioPolicyEngine"
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 #include "Engine.h"
28 #include <android-base/macros.h>
29 #include <AudioPolicyManagerObserver.h>
30 #include <PolicyAudioPort.h>
31 #include <IOProfile.h>
32 #include <AudioIODescriptorInterface.h>
33 #include <policy.h>
34 #include <media/AudioContainers.h>
35 #include <utils/String8.h>
36 #include <utils/Log.h>
37 
38 namespace android
39 {
40 namespace audio_policy
41 {
42 
43 struct legacy_strategy_map { const char *name; legacy_strategy id; };
getLegacyStrategy()44 static const std::vector<legacy_strategy_map>& getLegacyStrategy() {
45     static const std::vector<legacy_strategy_map> legacyStrategy = {
46         { "STRATEGY_NONE", STRATEGY_NONE },
47         { "STRATEGY_MEDIA", STRATEGY_MEDIA },
48         { "STRATEGY_PHONE", STRATEGY_PHONE },
49         { "STRATEGY_SONIFICATION", STRATEGY_SONIFICATION },
50         { "STRATEGY_SONIFICATION_RESPECTFUL", STRATEGY_SONIFICATION_RESPECTFUL },
51         { "STRATEGY_DTMF", STRATEGY_DTMF },
52         { "STRATEGY_ENFORCED_AUDIBLE", STRATEGY_ENFORCED_AUDIBLE },
53         { "STRATEGY_TRANSMITTED_THROUGH_SPEAKER", STRATEGY_TRANSMITTED_THROUGH_SPEAKER },
54         { "STRATEGY_ACCESSIBILITY", STRATEGY_ACCESSIBILITY },
55         { "STRATEGY_REROUTING", STRATEGY_REROUTING },
56         { "STRATEGY_PATCH", STRATEGY_REROUTING }, // boiler to manage stream patch volume
57     };
58     return legacyStrategy;
59 };
60 
Engine()61 Engine::Engine()
62 {
63     auto result = EngineBase::loadAudioPolicyEngineConfig();
64     ALOGE_IF(result.nbSkippedElement != 0,
65              "Policy Engine configuration is partially invalid, skipped %zu elements",
66              result.nbSkippedElement);
67 
68     auto legacyStrategy = getLegacyStrategy();
69     for (const auto &strategy : legacyStrategy) {
70         mLegacyStrategyMap[getProductStrategyByName(strategy.name)] = strategy.id;
71     }
72 }
73 
setForceUse(audio_policy_force_use_t usage,audio_policy_forced_cfg_t config)74 status_t Engine::setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config)
75 {
76     switch(usage) {
77     case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
78         if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
79             config != AUDIO_POLICY_FORCE_NONE) {
80             ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
81             return BAD_VALUE;
82         }
83         break;
84     case AUDIO_POLICY_FORCE_FOR_MEDIA:
85         if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
86             config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
87             config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
88             config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
89             config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
90             ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
91             return BAD_VALUE;
92         }
93         break;
94     case AUDIO_POLICY_FORCE_FOR_RECORD:
95         if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
96             config != AUDIO_POLICY_FORCE_NONE) {
97             ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
98             return BAD_VALUE;
99         }
100         break;
101     case AUDIO_POLICY_FORCE_FOR_DOCK:
102         if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
103             config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
104             config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
105             config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
106             config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
107             ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
108         }
109         break;
110     case AUDIO_POLICY_FORCE_FOR_SYSTEM:
111         if (config != AUDIO_POLICY_FORCE_NONE &&
112             config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
113             ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
114         }
115         break;
116     case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
117         if (config != AUDIO_POLICY_FORCE_NONE &&
118             config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
119             ALOGW("setForceUse() invalid config %d for HDMI_SYSTEM_AUDIO", config);
120         }
121         break;
122     case AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND:
123         if (config != AUDIO_POLICY_FORCE_NONE &&
124                 config != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER &&
125                 config != AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS &&
126                 config != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
127             ALOGW("setForceUse() invalid config %d for ENCODED_SURROUND", config);
128             return BAD_VALUE;
129         }
130         break;
131     case AUDIO_POLICY_FORCE_FOR_VIBRATE_RINGING:
132         if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_NONE) {
133             ALOGW("setForceUse() invalid config %d for FOR_VIBRATE_RINGING", config);
134             return BAD_VALUE;
135         }
136         break;
137     default:
138         ALOGW("setForceUse() invalid usage %d", usage);
139         break; // TODO return BAD_VALUE?
140     }
141     return EngineBase::setForceUse(usage, config);
142 }
143 
getDevicesForStrategyInt(legacy_strategy strategy,DeviceVector availableOutputDevices,DeviceVector availableInputDevices,const SwAudioOutputCollection & outputs) const144 DeviceVector Engine::getDevicesForStrategyInt(legacy_strategy strategy,
145                                               DeviceVector availableOutputDevices,
146                                               DeviceVector availableInputDevices,
147                                               const SwAudioOutputCollection &outputs) const
148 {
149     DeviceVector devices;
150 
151     switch (strategy) {
152 
153     case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
154         devices = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER);
155         break;
156 
157     case STRATEGY_SONIFICATION_RESPECTFUL:
158         if (isInCall() || outputs.isActiveLocally(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) {
159             devices = getDevicesForStrategyInt(
160                     STRATEGY_SONIFICATION, availableOutputDevices, availableInputDevices, outputs);
161         } else {
162             bool media_active_locally =
163                     outputs.isActiveLocally(toVolumeSource(AUDIO_STREAM_MUSIC),
164                                             SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)
165                     || outputs.isActiveLocally(
166                         toVolumeSource(AUDIO_STREAM_ACCESSIBILITY),
167                         SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY);
168             // routing is same as media without the "remote" device
169             availableOutputDevices.remove(availableOutputDevices.getDevicesFromType(
170                     AUDIO_DEVICE_OUT_REMOTE_SUBMIX));
171             devices = getDevicesForStrategyInt(STRATEGY_MEDIA,
172                     availableOutputDevices,
173                     availableInputDevices, outputs);
174             // if no media is playing on the device, check for mandatory use of "safe" speaker
175             // when media would have played on speaker, and the safe speaker path is available
176             if (!media_active_locally) {
177                 devices.replaceDevicesByType(
178                         AUDIO_DEVICE_OUT_SPEAKER,
179                         availableOutputDevices.getDevicesFromType(
180                                 AUDIO_DEVICE_OUT_SPEAKER_SAFE));
181             }
182         }
183         break;
184 
185     case STRATEGY_DTMF:
186         if (!isInCall()) {
187             // when off call, DTMF strategy follows the same rules as MEDIA strategy
188             devices = getDevicesForStrategyInt(
189                     STRATEGY_MEDIA, availableOutputDevices, availableInputDevices, outputs);
190             break;
191         }
192         // when in call, DTMF and PHONE strategies follow the same rules
193         FALLTHROUGH_INTENDED;
194 
195     case STRATEGY_PHONE:
196         // Force use of only devices on primary output if:
197         // - in call AND
198         //   - cannot route from voice call RX OR
199         //   - audio HAL version is < 3.0 and TX device is on the primary HW module
200         if (getPhoneState() == AUDIO_MODE_IN_CALL) {
201             audio_devices_t txDevice = getDeviceForInputSource(
202                     AUDIO_SOURCE_VOICE_COMMUNICATION)->type();
203             sp<AudioOutputDescriptor> primaryOutput = outputs.getPrimaryOutput();
204             DeviceVector availPrimaryInputDevices =
205                     availableInputDevices.getDevicesFromHwModule(primaryOutput->getModuleHandle());
206 
207             // TODO: getPrimaryOutput return only devices from first module in
208             // audio_policy_configuration.xml, hearing aid is not there, but it's
209             // a primary device
210             // FIXME: this is not the right way of solving this problem
211             DeviceVector availPrimaryOutputDevices = availableOutputDevices.getDevicesFromTypes(
212                     primaryOutput->supportedDevices().types());
213             availPrimaryOutputDevices.add(
214                     availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_HEARING_AID));
215 
216             if ((availableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
217                     String8(""), AUDIO_FORMAT_DEFAULT) == nullptr) ||
218                     ((availPrimaryInputDevices.getDevice(
219                             txDevice, String8(""), AUDIO_FORMAT_DEFAULT) != nullptr) &&
220                             (primaryOutput->getPolicyAudioPort()->getModuleVersionMajor() < 3))) {
221                 availableOutputDevices = availPrimaryOutputDevices;
222             }
223         }
224         // for phone strategy, we first consider the forced use and then the available devices by
225         // order of priority
226         switch (getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION)) {
227         case AUDIO_POLICY_FORCE_BT_SCO:
228             if (!isInCall() || strategy != STRATEGY_DTMF) {
229                 devices = availableOutputDevices.getDevicesFromType(
230                         AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT);
231                 if (!devices.isEmpty()) break;
232             }
233             devices = availableOutputDevices.getFirstDevicesFromTypes({
234                     AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, AUDIO_DEVICE_OUT_BLUETOOTH_SCO});
235             if (!devices.isEmpty()) break;
236             // if SCO device is requested but no SCO device is available, fall back to default case
237             FALLTHROUGH_INTENDED;
238 
239         default:    // FORCE_NONE
240             devices = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_HEARING_AID);
241             if (!devices.isEmpty()) break;
242             // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
243             if (!isInCall() &&
244                     (getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA) != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
245                      outputs.isA2dpSupported()) {
246                 devices = availableOutputDevices.getFirstDevicesFromTypes({
247                         AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
248                         AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES});
249                 if (!devices.isEmpty()) break;
250             }
251             devices = availableOutputDevices.getFirstDevicesFromTypes({
252                     AUDIO_DEVICE_OUT_WIRED_HEADPHONE, AUDIO_DEVICE_OUT_WIRED_HEADSET,
253                     AUDIO_DEVICE_OUT_LINE, AUDIO_DEVICE_OUT_USB_HEADSET,
254                     AUDIO_DEVICE_OUT_USB_DEVICE});
255             if (!devices.isEmpty()) break;
256             if (!isInCall()) {
257                 devices = availableOutputDevices.getFirstDevicesFromTypes({
258                         AUDIO_DEVICE_OUT_USB_ACCESSORY, AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,
259                         AUDIO_DEVICE_OUT_AUX_DIGITAL, AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET});
260                 if (!devices.isEmpty()) break;
261             }
262             devices = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_EARPIECE);
263             break;
264 
265         case AUDIO_POLICY_FORCE_SPEAKER:
266             // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
267             // A2DP speaker when forcing to speaker output
268             if (!isInCall() &&
269                     (getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA) != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
270                      outputs.isA2dpSupported()) {
271                 devices = availableOutputDevices.getDevicesFromType(
272                         AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER);
273                 if (!devices.isEmpty()) break;
274             }
275             if (!isInCall()) {
276                 devices = availableOutputDevices.getFirstDevicesFromTypes({
277                         AUDIO_DEVICE_OUT_USB_ACCESSORY, AUDIO_DEVICE_OUT_USB_DEVICE,
278                         AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET, AUDIO_DEVICE_OUT_AUX_DIGITAL,
279                         AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET});
280                 if (!devices.isEmpty()) break;
281             }
282             devices = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER);
283             break;
284         }
285     break;
286 
287     case STRATEGY_SONIFICATION:
288 
289         // If incall, just select the STRATEGY_PHONE device
290         if (isInCall() ||
291                 outputs.isActiveLocally(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) {
292             devices = getDevicesForStrategyInt(
293                     STRATEGY_PHONE, availableOutputDevices, availableInputDevices, outputs);
294             break;
295         }
296         FALLTHROUGH_INTENDED;
297 
298     case STRATEGY_ENFORCED_AUDIBLE:
299         // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
300         // except:
301         //   - when in call where it doesn't default to STRATEGY_PHONE behavior
302         //   - in countries where not enforced in which case it follows STRATEGY_MEDIA
303 
304         if ((strategy == STRATEGY_SONIFICATION) ||
305                 (getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
306             devices = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER);
307         }
308 
309         // if SCO headset is connected and we are told to use it, play ringtone over
310         // speaker and BT SCO
311         if (!availableOutputDevices.getDevicesFromTypes(getAudioDeviceOutAllScoSet()).isEmpty()) {
312             DeviceVector devices2;
313             devices2 = availableOutputDevices.getFirstDevicesFromTypes({
314                     AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET,
315                     AUDIO_DEVICE_OUT_BLUETOOTH_SCO});
316             // Use ONLY Bluetooth SCO output when ringing in vibration mode
317             if (!((getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
318                     && (strategy == STRATEGY_ENFORCED_AUDIBLE))) {
319                 if (getForceUse(AUDIO_POLICY_FORCE_FOR_VIBRATE_RINGING)
320                         == AUDIO_POLICY_FORCE_BT_SCO) {
321                     if (!devices2.isEmpty()) {
322                         devices = devices2;
323                         break;
324                     }
325                 }
326             }
327             // Use both Bluetooth SCO and phone default output when ringing in normal mode
328             if (getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) {
329                 if (strategy == STRATEGY_SONIFICATION) {
330                     devices.replaceDevicesByType(
331                             AUDIO_DEVICE_OUT_SPEAKER,
332                             availableOutputDevices.getDevicesFromType(
333                                     AUDIO_DEVICE_OUT_SPEAKER_SAFE));
334                 }
335                 if (!devices2.isEmpty()) {
336                     devices.add(devices2);
337                     break;
338                 }
339             }
340         }
341         // The second device used for sonification is the same as the device used by media strategy
342         FALLTHROUGH_INTENDED;
343 
344     case STRATEGY_ACCESSIBILITY:
345         if (strategy == STRATEGY_ACCESSIBILITY) {
346             // do not route accessibility prompts to a digital output currently configured with a
347             // compressed format as they would likely not be mixed and dropped.
348             for (size_t i = 0; i < outputs.size(); i++) {
349                 sp<AudioOutputDescriptor> desc = outputs.valueAt(i);
350                 if (desc->isActive() && !audio_is_linear_pcm(desc->getFormat())) {
351                     availableOutputDevices.remove(desc->devices().getDevicesFromTypes({
352                             AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_SPDIF,
353                             AUDIO_DEVICE_OUT_HDMI_ARC}));
354                 }
355             }
356             if (outputs.isActive(toVolumeSource(AUDIO_STREAM_RING)) ||
357                     outputs.isActive(toVolumeSource(AUDIO_STREAM_ALARM))) {
358                 return getDevicesForStrategyInt(
359                     STRATEGY_SONIFICATION, availableOutputDevices, availableInputDevices, outputs);
360             }
361             if (isInCall()) {
362                 return getDevicesForStrategyInt(
363                         STRATEGY_PHONE, availableOutputDevices, availableInputDevices, outputs);
364             }
365         }
366         // For other cases, STRATEGY_ACCESSIBILITY behaves like STRATEGY_MEDIA
367         FALLTHROUGH_INTENDED;
368 
369     // FIXME: STRATEGY_REROUTING follow STRATEGY_MEDIA for now
370     case STRATEGY_REROUTING:
371     case STRATEGY_MEDIA: {
372         DeviceVector devices2;
373         if (strategy != STRATEGY_SONIFICATION) {
374             // no sonification on remote submix (e.g. WFD)
375             sp<DeviceDescriptor> remoteSubmix;
376             if ((remoteSubmix = availableOutputDevices.getDevice(
377                     AUDIO_DEVICE_OUT_REMOTE_SUBMIX, String8("0"),
378                     AUDIO_FORMAT_DEFAULT)) != nullptr) {
379                 devices2.add(remoteSubmix);
380             }
381         }
382         if (isInCall() && (strategy == STRATEGY_MEDIA)) {
383             devices = getDevicesForStrategyInt(
384                     STRATEGY_PHONE, availableOutputDevices, availableInputDevices, outputs);
385             break;
386         }
387         // FIXME: Find a better solution to prevent routing to BT hearing aid(b/122931261).
388         if ((devices2.isEmpty()) &&
389                 (getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA) != AUDIO_POLICY_FORCE_NO_BT_A2DP)) {
390             devices2 = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_HEARING_AID);
391         }
392         if ((devices2.isEmpty()) &&
393             (getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA) == AUDIO_POLICY_FORCE_SPEAKER)) {
394             devices2 = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER);
395         }
396         if (devices2.isEmpty() && (getLastRemovableMediaDevices().size() > 0)) {
397             if ((getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA) != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
398                     outputs.isA2dpSupported()) {
399                 // Get the last connected device of wired and bluetooth a2dp
400                 devices2 = availableOutputDevices.getFirstDevicesFromTypes(
401                         getLastRemovableMediaDevices());
402             } else {
403                 // Get the last connected device of wired except bluetooth a2dp
404                 devices2 = availableOutputDevices.getFirstDevicesFromTypes(
405                         getLastRemovableMediaDevices(GROUP_WIRED));
406             }
407         }
408         if ((devices2.isEmpty()) && (strategy != STRATEGY_SONIFICATION)) {
409             // no sonification on aux digital (e.g. HDMI)
410             devices2 = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_AUX_DIGITAL);
411         }
412         if ((devices2.isEmpty()) &&
413                 (getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK) == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
414             devices2 = availableOutputDevices.getDevicesFromType(
415                     AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET);
416         }
417         if (devices2.isEmpty()) {
418             devices2 = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER);
419         }
420         DeviceVector devices3;
421         if (strategy == STRATEGY_MEDIA) {
422             // ARC, SPDIF and AUX_LINE can co-exist with others.
423             devices3 = availableOutputDevices.getDevicesFromTypes({
424                     AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_SPDIF, AUDIO_DEVICE_OUT_AUX_LINE});
425         }
426 
427         devices2.add(devices3);
428         // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
429         // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
430         devices.add(devices2);
431 
432         // If hdmi system audio mode is on, remove speaker out of output list.
433         if ((strategy == STRATEGY_MEDIA) &&
434             (getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO) ==
435                 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
436             devices.remove(devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
437         }
438 
439         // for STRATEGY_SONIFICATION:
440         // if SPEAKER was selected, and SPEAKER_SAFE is available, use SPEAKER_SAFE instead
441         if (strategy == STRATEGY_SONIFICATION) {
442             devices.replaceDevicesByType(
443                     AUDIO_DEVICE_OUT_SPEAKER,
444                     availableOutputDevices.getDevicesFromType(
445                             AUDIO_DEVICE_OUT_SPEAKER_SAFE));
446         }
447         } break;
448 
449     default:
450         ALOGW("getDevicesForStrategy() unknown strategy: %d", strategy);
451         break;
452     }
453 
454     if (devices.isEmpty()) {
455         ALOGV("getDevicesForStrategy() no device found for strategy %d", strategy);
456         sp<DeviceDescriptor> defaultOutputDevice = getApmObserver()->getDefaultOutputDevice();
457         if (defaultOutputDevice != nullptr) {
458             devices.add(defaultOutputDevice);
459         }
460         ALOGE_IF(devices.isEmpty(),
461                  "getDevicesForStrategy() no default device defined");
462     }
463 
464     ALOGVV("getDevices"
465            "ForStrategy() strategy %d, device %x", strategy, devices.types());
466     return devices;
467 }
468 
469 
getDeviceForInputSource(audio_source_t inputSource) const470 sp<DeviceDescriptor> Engine::getDeviceForInputSource(audio_source_t inputSource) const
471 {
472     const DeviceVector availableOutputDevices = getApmObserver()->getAvailableOutputDevices();
473     const DeviceVector availableInputDevices = getApmObserver()->getAvailableInputDevices();
474     const SwAudioOutputCollection &outputs = getApmObserver()->getOutputs();
475     DeviceVector availableDevices = availableInputDevices;
476     sp<AudioOutputDescriptor> primaryOutput = outputs.getPrimaryOutput();
477     DeviceVector availablePrimaryDevices = availableInputDevices.getDevicesFromHwModule(
478             primaryOutput->getModuleHandle());
479     sp<DeviceDescriptor> device;
480 
481     // when a call is active, force device selection to match source VOICE_COMMUNICATION
482     // for most other input sources to avoid rerouting call TX audio
483     if (isInCall()) {
484         switch (inputSource) {
485         case AUDIO_SOURCE_DEFAULT:
486         case AUDIO_SOURCE_MIC:
487         case AUDIO_SOURCE_VOICE_RECOGNITION:
488         case AUDIO_SOURCE_UNPROCESSED:
489         case AUDIO_SOURCE_HOTWORD:
490         case AUDIO_SOURCE_CAMCORDER:
491         case AUDIO_SOURCE_VOICE_PERFORMANCE:
492             inputSource = AUDIO_SOURCE_VOICE_COMMUNICATION;
493             break;
494         default:
495             break;
496         }
497     }
498 
499     switch (inputSource) {
500     case AUDIO_SOURCE_DEFAULT:
501     case AUDIO_SOURCE_MIC:
502         device = availableDevices.getDevice(
503                 AUDIO_DEVICE_IN_BLUETOOTH_A2DP, String8(""), AUDIO_FORMAT_DEFAULT);
504         if (device != nullptr) break;
505         if (getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO) {
506             device = availableDevices.getDevice(
507                     AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, String8(""), AUDIO_FORMAT_DEFAULT);
508             if (device != nullptr) break;
509         }
510         device = availableDevices.getFirstExistingDevice({
511                 AUDIO_DEVICE_IN_WIRED_HEADSET, AUDIO_DEVICE_IN_USB_HEADSET,
512                 AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_DEVICE_IN_BUILTIN_MIC});
513         break;
514 
515     case AUDIO_SOURCE_VOICE_COMMUNICATION:
516         // Allow only use of devices on primary input if in call and HAL does not support routing
517         // to voice call path.
518         if ((getPhoneState() == AUDIO_MODE_IN_CALL) &&
519                 (availableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
520                         String8(""), AUDIO_FORMAT_DEFAULT)) == nullptr) {
521             availableDevices = availablePrimaryDevices;
522         }
523 
524         switch (getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION)) {
525         case AUDIO_POLICY_FORCE_BT_SCO:
526             // if SCO device is requested but no SCO device is available, fall back to default case
527             device = availableDevices.getDevice(
528                     AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, String8(""), AUDIO_FORMAT_DEFAULT);
529             if (device != nullptr) {
530                 break;
531             }
532             FALLTHROUGH_INTENDED;
533 
534         default:    // FORCE_NONE
535             device = availableDevices.getFirstExistingDevice({
536                     AUDIO_DEVICE_IN_WIRED_HEADSET, AUDIO_DEVICE_IN_USB_HEADSET,
537                     AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_DEVICE_IN_BUILTIN_MIC});
538             break;
539 
540         case AUDIO_POLICY_FORCE_SPEAKER:
541             device = availableDevices.getFirstExistingDevice({
542                     AUDIO_DEVICE_IN_BACK_MIC, AUDIO_DEVICE_IN_BUILTIN_MIC});
543             break;
544         }
545         break;
546 
547     case AUDIO_SOURCE_VOICE_RECOGNITION:
548     case AUDIO_SOURCE_UNPROCESSED:
549     case AUDIO_SOURCE_HOTWORD:
550         if (inputSource == AUDIO_SOURCE_HOTWORD) {
551             availableDevices = availablePrimaryDevices;
552         }
553         if (getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO) {
554             device = availableDevices.getDevice(
555                     AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, String8(""), AUDIO_FORMAT_DEFAULT);
556             if (device != nullptr) break;
557         }
558         device = availableDevices.getFirstExistingDevice({
559                 AUDIO_DEVICE_IN_WIRED_HEADSET, AUDIO_DEVICE_IN_USB_HEADSET,
560                 AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_DEVICE_IN_BUILTIN_MIC});
561         break;
562     case AUDIO_SOURCE_CAMCORDER:
563         // For a device without built-in mic, adding usb device
564         device = availableDevices.getFirstExistingDevice({
565                 AUDIO_DEVICE_IN_BACK_MIC, AUDIO_DEVICE_IN_BUILTIN_MIC,
566                 AUDIO_DEVICE_IN_USB_DEVICE});
567         break;
568     case AUDIO_SOURCE_VOICE_DOWNLINK:
569     case AUDIO_SOURCE_VOICE_CALL:
570     case AUDIO_SOURCE_VOICE_UPLINK:
571         device = availableDevices.getDevice(
572                 AUDIO_DEVICE_IN_VOICE_CALL, String8(""), AUDIO_FORMAT_DEFAULT);
573         break;
574     case AUDIO_SOURCE_VOICE_PERFORMANCE:
575         device = availableDevices.getFirstExistingDevice({
576                 AUDIO_DEVICE_IN_WIRED_HEADSET, AUDIO_DEVICE_IN_USB_HEADSET,
577                 AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_DEVICE_IN_BUILTIN_MIC});
578         break;
579     case AUDIO_SOURCE_REMOTE_SUBMIX:
580         device = availableDevices.getDevice(
581                 AUDIO_DEVICE_IN_REMOTE_SUBMIX, String8(""), AUDIO_FORMAT_DEFAULT);
582         break;
583     case AUDIO_SOURCE_FM_TUNER:
584         device = availableDevices.getDevice(
585                 AUDIO_DEVICE_IN_FM_TUNER, String8(""), AUDIO_FORMAT_DEFAULT);
586         break;
587     case AUDIO_SOURCE_ECHO_REFERENCE:
588         device = availableDevices.getDevice(
589                 AUDIO_DEVICE_IN_ECHO_REFERENCE, String8(""), AUDIO_FORMAT_DEFAULT);
590         break;
591     default:
592         ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
593         break;
594     }
595     if (device == nullptr) {
596         ALOGV("getDeviceForInputSource() no device found for source %d", inputSource);
597         device = availableDevices.getDevice(
598                 AUDIO_DEVICE_IN_STUB, String8(""), AUDIO_FORMAT_DEFAULT);
599         ALOGE_IF(device == nullptr,
600                  "getDeviceForInputSource() no default device defined");
601     }
602     ALOGV_IF(device != nullptr,
603              "getDeviceForInputSource()input source %d, device %08x",
604              inputSource, device->type());
605     return device;
606 }
607 
updateDeviceSelectionCache()608 void Engine::updateDeviceSelectionCache()
609 {
610     for (const auto &iter : getProductStrategies()) {
611         const auto& strategy = iter.second;
612         auto devices = getDevicesForProductStrategy(strategy->getId());
613         mDevicesForStrategies[strategy->getId()] = devices;
614         strategy->setDeviceTypes(devices.types());
615         strategy->setDeviceAddress(devices.getFirstValidAddress().c_str());
616     }
617 }
618 
getDevicesForProductStrategy(product_strategy_t strategy) const619 DeviceVector Engine::getDevicesForProductStrategy(product_strategy_t strategy) const {
620     DeviceVector availableOutputDevices = getApmObserver()->getAvailableOutputDevices();
621 
622     // check if this strategy has a preferred device that is available,
623     // if yes, give priority to it
624     AudioDeviceTypeAddr preferredStrategyDevice;
625     const status_t status = getPreferredDeviceForStrategy(strategy, preferredStrategyDevice);
626     if (status == NO_ERROR) {
627         // there is a preferred device, is it available?
628         sp<DeviceDescriptor> preferredAvailableDevDescr = availableOutputDevices.getDevice(
629                 preferredStrategyDevice.mType,
630                 String8(preferredStrategyDevice.mAddress.c_str()),
631                 AUDIO_FORMAT_DEFAULT);
632         if (preferredAvailableDevDescr != nullptr) {
633             ALOGVV("%s using pref device 0x%08x/%s for strategy %u", __FUNCTION__,
634                    preferredStrategyDevice.mType, preferredStrategyDevice.mAddress, strategy);
635             return DeviceVector(preferredAvailableDevDescr);
636         }
637     }
638 
639     DeviceVector availableInputDevices = getApmObserver()->getAvailableInputDevices();
640     const SwAudioOutputCollection& outputs = getApmObserver()->getOutputs();
641     auto legacyStrategy = mLegacyStrategyMap.find(strategy) != end(mLegacyStrategyMap) ?
642                           mLegacyStrategyMap.at(strategy) : STRATEGY_NONE;
643     return getDevicesForStrategyInt(legacyStrategy,
644                                     availableOutputDevices,
645                                     availableInputDevices, outputs);
646 }
647 
getOutputDevicesForAttributes(const audio_attributes_t & attributes,const sp<DeviceDescriptor> & preferredDevice,bool fromCache) const648 DeviceVector Engine::getOutputDevicesForAttributes(const audio_attributes_t &attributes,
649                                                    const sp<DeviceDescriptor> &preferredDevice,
650                                                    bool fromCache) const
651 {
652     // First check for explict routing device
653     if (preferredDevice != nullptr) {
654         ALOGV("%s explicit Routing on device %s", __func__, preferredDevice->toString().c_str());
655         return DeviceVector(preferredDevice);
656     }
657     product_strategy_t strategy = getProductStrategyForAttributes(attributes);
658     const DeviceVector availableOutputDevices = getApmObserver()->getAvailableOutputDevices();
659     const SwAudioOutputCollection &outputs = getApmObserver()->getOutputs();
660     //
661     // @TODO: what is the priority of explicit routing? Shall it be considered first as it used to
662     // be by APM?
663     //
664     // Honor explicit routing requests only if all active clients have a preferred route in which
665     // case the last active client route is used
666     sp<DeviceDescriptor> device = findPreferredDevice(outputs, strategy, availableOutputDevices);
667     if (device != nullptr) {
668         return DeviceVector(device);
669     }
670 
671     return fromCache? mDevicesForStrategies.at(strategy) : getDevicesForProductStrategy(strategy);
672 }
673 
getOutputDevicesForStream(audio_stream_type_t stream,bool fromCache) const674 DeviceVector Engine::getOutputDevicesForStream(audio_stream_type_t stream, bool fromCache) const
675 {
676     auto attributes = getAttributesForStreamType(stream);
677     return getOutputDevicesForAttributes(attributes, nullptr, fromCache);
678 }
679 
getInputDeviceForAttributes(const audio_attributes_t & attr,sp<AudioPolicyMix> * mix) const680 sp<DeviceDescriptor> Engine::getInputDeviceForAttributes(const audio_attributes_t &attr,
681                                                          sp<AudioPolicyMix> *mix) const
682 {
683     const auto &policyMixes = getApmObserver()->getAudioPolicyMixCollection();
684     const auto availableInputDevices = getApmObserver()->getAvailableInputDevices();
685     const auto &inputs = getApmObserver()->getInputs();
686     std::string address;
687 
688     //
689     // Explicit Routing ??? what is the priority of explicit routing? Shall it be considered
690     // first as it used to be by APM?
691     //
692     // Honor explicit routing requests only if all active clients have a preferred route in which
693     // case the last active client route is used
694     sp<DeviceDescriptor> device =
695             findPreferredDevice(inputs, attr.source, availableInputDevices);
696     if (device != nullptr) {
697         return device;
698     }
699 
700     device = policyMixes.getDeviceAndMixForInputSource(attr.source, availableInputDevices, mix);
701     if (device != nullptr) {
702         return device;
703     }
704 
705     device = getDeviceForInputSource(attr.source);
706     if (device == nullptr || !audio_is_remote_submix_device(device->type())) {
707         // Return immediately if the device is null or it is not a remote submix device.
708         return device;
709     }
710 
711     // For remote submix device, try to find the device by address.
712     address = "0";
713     std::size_t pos;
714     std::string tags { attr.tags };
715     if ((pos = tags.find("addr=")) != std::string::npos) {
716         address = tags.substr(pos + std::strlen("addr="));
717     }
718     return availableInputDevices.getDevice(device->type(),
719                                            String8(address.c_str()),
720                                            AUDIO_FORMAT_DEFAULT);
721 }
722 
723 } // namespace audio_policy
724 } // namespace android
725 
726 
727