• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "AudioPolicyManagerBase"
18 //#define LOG_NDEBUG 0
19 #include <utils/Log.h>
20 #include <hardware_legacy/AudioPolicyManagerBase.h>
21 #include <hardware/audio_effect.h>
22 #include <math.h>
23 
24 namespace android_audio_legacy {
25 
26 // ----------------------------------------------------------------------------
27 // AudioPolicyInterface implementation
28 // ----------------------------------------------------------------------------
29 
30 
setDeviceConnectionState(AudioSystem::audio_devices device,AudioSystem::device_connection_state state,const char * device_address)31 status_t AudioPolicyManagerBase::setDeviceConnectionState(AudioSystem::audio_devices device,
32                                                   AudioSystem::device_connection_state state,
33                                                   const char *device_address)
34 {
35 
36     LOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
37 
38     // connect/disconnect only 1 device at a time
39     if (AudioSystem::popCount(device) != 1) return BAD_VALUE;
40 
41     if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
42         LOGE("setDeviceConnectionState() invalid address: %s", device_address);
43         return BAD_VALUE;
44     }
45 
46     // handle output devices
47     if (AudioSystem::isOutputDevice(device)) {
48 
49 #ifndef WITH_A2DP
50         if (AudioSystem::isA2dpDevice(device)) {
51             LOGE("setDeviceConnectionState() invalid device: %x", device);
52             return BAD_VALUE;
53         }
54 #endif
55 
56         switch (state)
57         {
58         // handle output device connection
59         case AudioSystem::DEVICE_STATE_AVAILABLE:
60             if (mAvailableOutputDevices & device) {
61                 LOGW("setDeviceConnectionState() device already connected: %x", device);
62                 return INVALID_OPERATION;
63             }
64             LOGV("setDeviceConnectionState() connecting device %x", device);
65 
66             // register new device as available
67             mAvailableOutputDevices |= device;
68 
69 #ifdef WITH_A2DP
70             // handle A2DP device connection
71             if (AudioSystem::isA2dpDevice(device)) {
72                 status_t status = handleA2dpConnection(device, device_address);
73                 if (status != NO_ERROR) {
74                     mAvailableOutputDevices &= ~device;
75                     return status;
76                 }
77             } else
78 #endif
79             {
80                 if (AudioSystem::isBluetoothScoDevice(device)) {
81                     LOGV("setDeviceConnectionState() BT SCO  device, address %s", device_address);
82                     // keep track of SCO device address
83                     mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
84                 }
85             }
86             break;
87         // handle output device disconnection
88         case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
89             if (!(mAvailableOutputDevices & device)) {
90                 LOGW("setDeviceConnectionState() device not connected: %x", device);
91                 return INVALID_OPERATION;
92             }
93 
94 
95             LOGV("setDeviceConnectionState() disconnecting device %x", device);
96             // remove device from available output devices
97             mAvailableOutputDevices &= ~device;
98 
99 #ifdef WITH_A2DP
100             // handle A2DP device disconnection
101             if (AudioSystem::isA2dpDevice(device)) {
102                 status_t status = handleA2dpDisconnection(device, device_address);
103                 if (status != NO_ERROR) {
104                     mAvailableOutputDevices |= device;
105                     return status;
106                 }
107             } else
108 #endif
109             {
110                 if (AudioSystem::isBluetoothScoDevice(device)) {
111                     mScoDeviceAddress = "";
112                 }
113             }
114             } break;
115 
116         default:
117             LOGE("setDeviceConnectionState() invalid state: %x", state);
118             return BAD_VALUE;
119         }
120 
121         // request routing change if necessary
122         uint32_t newDevice = getNewDevice(mHardwareOutput, false);
123 #ifdef WITH_A2DP
124         checkA2dpSuspend();
125         checkOutputForAllStrategies();
126         // A2DP outputs must be closed after checkOutputForAllStrategies() is executed
127         if (state == AudioSystem::DEVICE_STATE_UNAVAILABLE && AudioSystem::isA2dpDevice(device)) {
128             closeA2dpOutputs();
129         }
130 #endif
131         updateDeviceForStrategy();
132         setOutputDevice(mHardwareOutput, newDevice);
133 
134         if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET) {
135             device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
136         } else if (device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO ||
137                    device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
138                    device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
139             device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
140         } else {
141             return NO_ERROR;
142         }
143     }
144     // handle input devices
145     if (AudioSystem::isInputDevice(device)) {
146 
147         switch (state)
148         {
149         // handle input device connection
150         case AudioSystem::DEVICE_STATE_AVAILABLE: {
151             if (mAvailableInputDevices & device) {
152                 LOGW("setDeviceConnectionState() device already connected: %d", device);
153                 return INVALID_OPERATION;
154             }
155             mAvailableInputDevices |= device;
156             }
157             break;
158 
159         // handle input device disconnection
160         case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
161             if (!(mAvailableInputDevices & device)) {
162                 LOGW("setDeviceConnectionState() device not connected: %d", device);
163                 return INVALID_OPERATION;
164             }
165             mAvailableInputDevices &= ~device;
166             } break;
167 
168         default:
169             LOGE("setDeviceConnectionState() invalid state: %x", state);
170             return BAD_VALUE;
171         }
172 
173         audio_io_handle_t activeInput = getActiveInput();
174         if (activeInput != 0) {
175             AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
176             uint32_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
177             if (newDevice != inputDesc->mDevice) {
178                 LOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
179                         inputDesc->mDevice, newDevice, activeInput);
180                 inputDesc->mDevice = newDevice;
181                 AudioParameter param = AudioParameter();
182                 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
183                 mpClientInterface->setParameters(activeInput, param.toString());
184             }
185         }
186 
187         return NO_ERROR;
188     }
189 
190     LOGW("setDeviceConnectionState() invalid device: %x", device);
191     return BAD_VALUE;
192 }
193 
getDeviceConnectionState(AudioSystem::audio_devices device,const char * device_address)194 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(AudioSystem::audio_devices device,
195                                                   const char *device_address)
196 {
197     AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
198     String8 address = String8(device_address);
199     if (AudioSystem::isOutputDevice(device)) {
200         if (device & mAvailableOutputDevices) {
201 #ifdef WITH_A2DP
202             if (AudioSystem::isA2dpDevice(device) &&
203                 address != "" && mA2dpDeviceAddress != address) {
204                 return state;
205             }
206 #endif
207             if (AudioSystem::isBluetoothScoDevice(device) &&
208                 address != "" && mScoDeviceAddress != address) {
209                 return state;
210             }
211             state = AudioSystem::DEVICE_STATE_AVAILABLE;
212         }
213     } else if (AudioSystem::isInputDevice(device)) {
214         if (device & mAvailableInputDevices) {
215             state = AudioSystem::DEVICE_STATE_AVAILABLE;
216         }
217     }
218 
219     return state;
220 }
221 
setPhoneState(int state)222 void AudioPolicyManagerBase::setPhoneState(int state)
223 {
224     LOGV("setPhoneState() state %d", state);
225     uint32_t newDevice = 0;
226     if (state < 0 || state >= AudioSystem::NUM_MODES) {
227         LOGW("setPhoneState() invalid state %d", state);
228         return;
229     }
230 
231     if (state == mPhoneState ) {
232         LOGW("setPhoneState() setting same state %d", state);
233         return;
234     }
235 
236     // if leaving call state, handle special case of active streams
237     // pertaining to sonification strategy see handleIncallSonification()
238     if (isInCall()) {
239         LOGV("setPhoneState() in call state management: new state is %d", state);
240         for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
241             handleIncallSonification(stream, false, true);
242         }
243     }
244 
245     // store previous phone state for management of sonification strategy below
246     int oldState = mPhoneState;
247     mPhoneState = state;
248     bool force = false;
249 
250     // are we entering or starting a call
251     if (!isStateInCall(oldState) && isStateInCall(state)) {
252         LOGV("  Entering call in setPhoneState()");
253         // force routing command to audio hardware when starting a call
254         // even if no device change is needed
255         force = true;
256     } else if (isStateInCall(oldState) && !isStateInCall(state)) {
257         LOGV("  Exiting call in setPhoneState()");
258         // force routing command to audio hardware when exiting a call
259         // even if no device change is needed
260         force = true;
261     } else if (isStateInCall(state) && (state != oldState)) {
262         LOGV("  Switching between telephony and VoIP in setPhoneState()");
263         // force routing command to audio hardware when switching between telephony and VoIP
264         // even if no device change is needed
265         force = true;
266     }
267 
268     // check for device and output changes triggered by new phone state
269     newDevice = getNewDevice(mHardwareOutput, false);
270 #ifdef WITH_A2DP
271     checkA2dpSuspend();
272     checkOutputForAllStrategies();
273 #endif
274     updateDeviceForStrategy();
275 
276     AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
277 
278     // force routing command to audio hardware when ending call
279     // even if no device change is needed
280     if (isStateInCall(oldState) && newDevice == 0) {
281         newDevice = hwOutputDesc->device();
282     }
283 
284     // when changing from ring tone to in call mode, mute the ringing tone
285     // immediately and delay the route change to avoid sending the ring tone
286     // tail into the earpiece or headset.
287     int delayMs = 0;
288     if (isStateInCall(state) && oldState == AudioSystem::MODE_RINGTONE) {
289         // delay the device change command by twice the output latency to have some margin
290         // and be sure that audio buffers not yet affected by the mute are out when
291         // we actually apply the route change
292         delayMs = hwOutputDesc->mLatency*2;
293         setStreamMute(AudioSystem::RING, true, mHardwareOutput);
294     }
295 
296     // change routing is necessary
297     setOutputDevice(mHardwareOutput, newDevice, force, delayMs);
298 
299     // if entering in call state, handle special case of active streams
300     // pertaining to sonification strategy see handleIncallSonification()
301     if (isStateInCall(state)) {
302         LOGV("setPhoneState() in call state management: new state is %d", state);
303         // unmute the ringing tone after a sufficient delay if it was muted before
304         // setting output device above
305         if (oldState == AudioSystem::MODE_RINGTONE) {
306             setStreamMute(AudioSystem::RING, false, mHardwareOutput, MUTE_TIME_MS);
307         }
308         for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
309             handleIncallSonification(stream, true, true);
310         }
311     }
312 
313     // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
314     if (state == AudioSystem::MODE_RINGTONE &&
315         isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
316         mLimitRingtoneVolume = true;
317     } else {
318         mLimitRingtoneVolume = false;
319     }
320 }
321 
setRingerMode(uint32_t mode,uint32_t mask)322 void AudioPolicyManagerBase::setRingerMode(uint32_t mode, uint32_t mask)
323 {
324     LOGV("setRingerMode() mode %x, mask %x", mode, mask);
325 
326     mRingerMode = mode;
327 }
328 
setForceUse(AudioSystem::force_use usage,AudioSystem::forced_config config)329 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
330 {
331     LOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
332 
333     bool forceVolumeReeval = false;
334     switch(usage) {
335     case AudioSystem::FOR_COMMUNICATION:
336         if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
337             config != AudioSystem::FORCE_NONE) {
338             LOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
339             return;
340         }
341         forceVolumeReeval = true;
342         mForceUse[usage] = config;
343         break;
344     case AudioSystem::FOR_MEDIA:
345         if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
346             config != AudioSystem::FORCE_WIRED_ACCESSORY &&
347             config != AudioSystem::FORCE_ANALOG_DOCK &&
348             config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE) {
349             LOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
350             return;
351         }
352         mForceUse[usage] = config;
353         break;
354     case AudioSystem::FOR_RECORD:
355         if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
356             config != AudioSystem::FORCE_NONE) {
357             LOGW("setForceUse() invalid config %d for FOR_RECORD", config);
358             return;
359         }
360         mForceUse[usage] = config;
361         break;
362     case AudioSystem::FOR_DOCK:
363         if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
364             config != AudioSystem::FORCE_BT_DESK_DOCK &&
365             config != AudioSystem::FORCE_WIRED_ACCESSORY &&
366             config != AudioSystem::FORCE_ANALOG_DOCK &&
367             config != AudioSystem::FORCE_DIGITAL_DOCK) {
368             LOGW("setForceUse() invalid config %d for FOR_DOCK", config);
369         }
370         forceVolumeReeval = true;
371         mForceUse[usage] = config;
372         break;
373     default:
374         LOGW("setForceUse() invalid usage %d", usage);
375         break;
376     }
377 
378     // check for device and output changes triggered by new phone state
379     uint32_t newDevice = getNewDevice(mHardwareOutput, false);
380 #ifdef WITH_A2DP
381     checkA2dpSuspend();
382     checkOutputForAllStrategies();
383 #endif
384     updateDeviceForStrategy();
385     setOutputDevice(mHardwareOutput, newDevice);
386     if (forceVolumeReeval) {
387         applyStreamVolumes(mHardwareOutput, newDevice, 0, true);
388     }
389 
390     audio_io_handle_t activeInput = getActiveInput();
391     if (activeInput != 0) {
392         AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
393         newDevice = getDeviceForInputSource(inputDesc->mInputSource);
394         if (newDevice != inputDesc->mDevice) {
395             LOGV("setForceUse() changing device from %x to %x for input %d",
396                     inputDesc->mDevice, newDevice, activeInput);
397             inputDesc->mDevice = newDevice;
398             AudioParameter param = AudioParameter();
399             param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
400             mpClientInterface->setParameters(activeInput, param.toString());
401         }
402     }
403 
404 }
405 
getForceUse(AudioSystem::force_use usage)406 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
407 {
408     return mForceUse[usage];
409 }
410 
setSystemProperty(const char * property,const char * value)411 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
412 {
413     LOGV("setSystemProperty() property %s, value %s", property, value);
414     if (strcmp(property, "ro.camera.sound.forced") == 0) {
415         if (atoi(value)) {
416             LOGV("ENFORCED_AUDIBLE cannot be muted");
417             mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false;
418         } else {
419             LOGV("ENFORCED_AUDIBLE can be muted");
420             mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true;
421         }
422     }
423 }
424 
getOutput(AudioSystem::stream_type stream,uint32_t samplingRate,uint32_t format,uint32_t channels,AudioSystem::output_flags flags)425 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
426                                     uint32_t samplingRate,
427                                     uint32_t format,
428                                     uint32_t channels,
429                                     AudioSystem::output_flags flags)
430 {
431     audio_io_handle_t output = 0;
432     uint32_t latency = 0;
433     routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
434     uint32_t device = getDeviceForStrategy(strategy);
435     LOGV("getOutput() stream %d, samplingRate %d, format %d, channels %x, flags %x", stream, samplingRate, format, channels, flags);
436 
437 #ifdef AUDIO_POLICY_TEST
438     if (mCurOutput != 0) {
439         LOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channels %x, mDirectOutput %d",
440                 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
441 
442         if (mTestOutputs[mCurOutput] == 0) {
443             LOGV("getOutput() opening test output");
444             AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
445             outputDesc->mDevice = mTestDevice;
446             outputDesc->mSamplingRate = mTestSamplingRate;
447             outputDesc->mFormat = mTestFormat;
448             outputDesc->mChannels = mTestChannels;
449             outputDesc->mLatency = mTestLatencyMs;
450             outputDesc->mFlags = (AudioSystem::output_flags)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
451             outputDesc->mRefCount[stream] = 0;
452             mTestOutputs[mCurOutput] = mpClientInterface->openOutput(&outputDesc->mDevice,
453                                             &outputDesc->mSamplingRate,
454                                             &outputDesc->mFormat,
455                                             &outputDesc->mChannels,
456                                             &outputDesc->mLatency,
457                                             outputDesc->mFlags);
458             if (mTestOutputs[mCurOutput]) {
459                 AudioParameter outputCmd = AudioParameter();
460                 outputCmd.addInt(String8("set_id"),mCurOutput);
461                 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
462                 addOutput(mTestOutputs[mCurOutput], outputDesc);
463             }
464         }
465         return mTestOutputs[mCurOutput];
466     }
467 #endif //AUDIO_POLICY_TEST
468 
469     // open a direct output if required by specified parameters
470     if (needsDirectOuput(stream, samplingRate, format, channels, flags, device)) {
471 
472         LOGV("getOutput() opening direct output device %x", device);
473         AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
474         outputDesc->mDevice = device;
475         outputDesc->mSamplingRate = samplingRate;
476         outputDesc->mFormat = format;
477         outputDesc->mChannels = channels;
478         outputDesc->mLatency = 0;
479         outputDesc->mFlags = (AudioSystem::output_flags)(flags | AudioSystem::OUTPUT_FLAG_DIRECT);
480         outputDesc->mRefCount[stream] = 0;
481         outputDesc->mStopTime[stream] = 0;
482         output = mpClientInterface->openOutput(&outputDesc->mDevice,
483                                         &outputDesc->mSamplingRate,
484                                         &outputDesc->mFormat,
485                                         &outputDesc->mChannels,
486                                         &outputDesc->mLatency,
487                                         outputDesc->mFlags);
488 
489         // only accept an output with the requeted parameters
490         if (output == 0 ||
491             (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
492             (format != 0 && format != outputDesc->mFormat) ||
493             (channels != 0 && channels != outputDesc->mChannels)) {
494             LOGV("getOutput() failed opening direct output: samplingRate %d, format %d, channels %d",
495                     samplingRate, format, channels);
496             if (output != 0) {
497                 mpClientInterface->closeOutput(output);
498             }
499             delete outputDesc;
500             return 0;
501         }
502         addOutput(output, outputDesc);
503         return output;
504     }
505 
506     if (channels != 0 && channels != AudioSystem::CHANNEL_OUT_MONO &&
507         channels != AudioSystem::CHANNEL_OUT_STEREO) {
508         return 0;
509     }
510     // open a non direct output
511 
512     // get which output is suitable for the specified stream. The actual routing change will happen
513     // when startOutput() will be called
514     uint32_t a2dpDevice = device & AudioSystem::DEVICE_OUT_ALL_A2DP;
515     if (AudioSystem::popCount((AudioSystem::audio_devices)device) == 2) {
516 #ifdef WITH_A2DP
517         if (a2dpUsedForSonification() && a2dpDevice != 0) {
518             // if playing on 2 devices among which one is A2DP, use duplicated output
519             LOGV("getOutput() using duplicated output");
520             LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device in multiple %x selected but A2DP output not opened", device);
521             output = mDuplicatedOutput;
522         } else
523 #endif
524         {
525             // if playing on 2 devices among which none is A2DP, use hardware output
526             output = mHardwareOutput;
527         }
528         LOGV("getOutput() using output %d for 2 devices %x", output, device);
529     } else {
530 #ifdef WITH_A2DP
531         if (a2dpDevice != 0) {
532             // if playing on A2DP device, use a2dp output
533             LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device %x selected but A2DP output not opened", device);
534             output = mA2dpOutput;
535         } else
536 #endif
537         {
538             // if playing on not A2DP device, use hardware output
539             output = mHardwareOutput;
540         }
541     }
542 
543 
544     LOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d, format %d, channels %x, flags %x",
545                 stream, samplingRate, format, channels, flags);
546 
547     return output;
548 }
549 
startOutput(audio_io_handle_t output,AudioSystem::stream_type stream,int session)550 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
551                                              AudioSystem::stream_type stream,
552                                              int session)
553 {
554     LOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
555     ssize_t index = mOutputs.indexOfKey(output);
556     if (index < 0) {
557         LOGW("startOutput() unknow output %d", output);
558         return BAD_VALUE;
559     }
560 
561     AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
562     routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
563 
564 #ifdef WITH_A2DP
565     if (mA2dpOutput != 0  && !a2dpUsedForSonification() &&
566             (strategy == STRATEGY_SONIFICATION || strategy == STRATEGY_ENFORCED_AUDIBLE)) {
567         setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
568     }
569 #endif
570 
571     // incremenent usage count for this stream on the requested output:
572     // NOTE that the usage count is the same for duplicated output and hardware output which is
573     // necassary for a correct control of hardware output routing by startOutput() and stopOutput()
574     outputDesc->changeRefCount(stream, 1);
575 
576     uint32_t prevDevice = outputDesc->mDevice;
577     setOutputDevice(output, getNewDevice(output));
578 
579     // handle special case for sonification while in call
580     if (isInCall()) {
581         handleIncallSonification(stream, true, false);
582     }
583 
584     // apply volume rules for current stream and device if necessary
585     checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, outputDesc->device());
586 
587     // FIXME: need a delay to make sure that audio path switches to speaker before sound
588     // starts. Should be platform specific?
589     if (stream == AudioSystem::ENFORCED_AUDIBLE &&
590             prevDevice != outputDesc->mDevice) {
591         usleep(outputDesc->mLatency*4*1000);
592     }
593 
594     return NO_ERROR;
595 }
596 
stopOutput(audio_io_handle_t output,AudioSystem::stream_type stream,int session)597 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
598                                             AudioSystem::stream_type stream,
599                                             int session)
600 {
601     LOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
602     ssize_t index = mOutputs.indexOfKey(output);
603     if (index < 0) {
604         LOGW("stopOutput() unknow output %d", output);
605         return BAD_VALUE;
606     }
607 
608     AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
609     routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
610 
611     // handle special case for sonification while in call
612     if (isInCall()) {
613         handleIncallSonification(stream, false, false);
614     }
615 
616     if (outputDesc->mRefCount[stream] > 0) {
617         // decrement usage count of this stream on the output
618         outputDesc->changeRefCount(stream, -1);
619         // store time at which the stream was stopped - see isStreamActive()
620         outputDesc->mStopTime[stream] = systemTime();
621 
622         setOutputDevice(output, getNewDevice(output), false, outputDesc->mLatency*2);
623 
624 #ifdef WITH_A2DP
625         if (mA2dpOutput != 0 && !a2dpUsedForSonification() &&
626                 (strategy == STRATEGY_SONIFICATION || strategy == STRATEGY_ENFORCED_AUDIBLE)) {
627             setStrategyMute(STRATEGY_MEDIA,
628                             false,
629                             mA2dpOutput,
630                             mOutputs.valueFor(mHardwareOutput)->mLatency*2);
631         }
632 #endif
633         if (output != mHardwareOutput) {
634             setOutputDevice(mHardwareOutput, getNewDevice(mHardwareOutput), true);
635         }
636         return NO_ERROR;
637     } else {
638         LOGW("stopOutput() refcount is already 0 for output %d", output);
639         return INVALID_OPERATION;
640     }
641 }
642 
releaseOutput(audio_io_handle_t output)643 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
644 {
645     LOGV("releaseOutput() %d", output);
646     ssize_t index = mOutputs.indexOfKey(output);
647     if (index < 0) {
648         LOGW("releaseOutput() releasing unknown output %d", output);
649         return;
650     }
651 
652 #ifdef AUDIO_POLICY_TEST
653     int testIndex = testOutputIndex(output);
654     if (testIndex != 0) {
655         AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
656         if (outputDesc->refCount() == 0) {
657             mpClientInterface->closeOutput(output);
658             delete mOutputs.valueAt(index);
659             mOutputs.removeItem(output);
660             mTestOutputs[testIndex] = 0;
661         }
662         return;
663     }
664 #endif //AUDIO_POLICY_TEST
665 
666     if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
667         mpClientInterface->closeOutput(output);
668         delete mOutputs.valueAt(index);
669         mOutputs.removeItem(output);
670     }
671 }
672 
getInput(int inputSource,uint32_t samplingRate,uint32_t format,uint32_t channels,AudioSystem::audio_in_acoustics acoustics)673 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
674                                     uint32_t samplingRate,
675                                     uint32_t format,
676                                     uint32_t channels,
677                                     AudioSystem::audio_in_acoustics acoustics)
678 {
679     audio_io_handle_t input = 0;
680     uint32_t device = getDeviceForInputSource(inputSource);
681 
682     LOGV("getInput() inputSource %d, samplingRate %d, format %d, channels %x, acoustics %x", inputSource, samplingRate, format, channels, acoustics);
683 
684     if (device == 0) {
685         return 0;
686     }
687 
688     // adapt channel selection to input source
689     switch(inputSource) {
690     case AUDIO_SOURCE_VOICE_UPLINK:
691         channels = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
692         break;
693     case AUDIO_SOURCE_VOICE_DOWNLINK:
694         channels = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
695         break;
696     case AUDIO_SOURCE_VOICE_CALL:
697         channels = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
698         break;
699     default:
700         break;
701     }
702 
703     AudioInputDescriptor *inputDesc = new AudioInputDescriptor();
704 
705     inputDesc->mInputSource = inputSource;
706     inputDesc->mDevice = device;
707     inputDesc->mSamplingRate = samplingRate;
708     inputDesc->mFormat = format;
709     inputDesc->mChannels = channels;
710     inputDesc->mAcoustics = acoustics;
711     inputDesc->mRefCount = 0;
712     input = mpClientInterface->openInput(&inputDesc->mDevice,
713                                     &inputDesc->mSamplingRate,
714                                     &inputDesc->mFormat,
715                                     &inputDesc->mChannels,
716                                     inputDesc->mAcoustics);
717 
718     // only accept input with the exact requested set of parameters
719     if (input == 0 ||
720         (samplingRate != inputDesc->mSamplingRate) ||
721         (format != inputDesc->mFormat) ||
722         (channels != inputDesc->mChannels)) {
723         LOGV("getInput() failed opening input: samplingRate %d, format %d, channels %d",
724                 samplingRate, format, channels);
725         if (input != 0) {
726             mpClientInterface->closeInput(input);
727         }
728         delete inputDesc;
729         return 0;
730     }
731     mInputs.add(input, inputDesc);
732     return input;
733 }
734 
startInput(audio_io_handle_t input)735 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
736 {
737     LOGV("startInput() input %d", input);
738     ssize_t index = mInputs.indexOfKey(input);
739     if (index < 0) {
740         LOGW("startInput() unknow input %d", input);
741         return BAD_VALUE;
742     }
743     AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
744 
745 #ifdef AUDIO_POLICY_TEST
746     if (mTestInput == 0)
747 #endif //AUDIO_POLICY_TEST
748     {
749         // refuse 2 active AudioRecord clients at the same time
750         if (getActiveInput() != 0) {
751             LOGW("startInput() input %d failed: other input already started", input);
752             return INVALID_OPERATION;
753         }
754     }
755 
756     AudioParameter param = AudioParameter();
757     param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
758 
759     param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
760     LOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
761 
762     mpClientInterface->setParameters(input, param.toString());
763 
764     inputDesc->mRefCount = 1;
765     return NO_ERROR;
766 }
767 
stopInput(audio_io_handle_t input)768 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
769 {
770     LOGV("stopInput() input %d", input);
771     ssize_t index = mInputs.indexOfKey(input);
772     if (index < 0) {
773         LOGW("stopInput() unknow input %d", input);
774         return BAD_VALUE;
775     }
776     AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
777 
778     if (inputDesc->mRefCount == 0) {
779         LOGW("stopInput() input %d already stopped", input);
780         return INVALID_OPERATION;
781     } else {
782         AudioParameter param = AudioParameter();
783         param.addInt(String8(AudioParameter::keyRouting), 0);
784         mpClientInterface->setParameters(input, param.toString());
785         inputDesc->mRefCount = 0;
786         return NO_ERROR;
787     }
788 }
789 
releaseInput(audio_io_handle_t input)790 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
791 {
792     LOGV("releaseInput() %d", input);
793     ssize_t index = mInputs.indexOfKey(input);
794     if (index < 0) {
795         LOGW("releaseInput() releasing unknown input %d", input);
796         return;
797     }
798     mpClientInterface->closeInput(input);
799     delete mInputs.valueAt(index);
800     mInputs.removeItem(input);
801     LOGV("releaseInput() exit");
802 }
803 
initStreamVolume(AudioSystem::stream_type stream,int indexMin,int indexMax)804 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
805                                             int indexMin,
806                                             int indexMax)
807 {
808     LOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
809     if (indexMin < 0 || indexMin >= indexMax) {
810         LOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
811         return;
812     }
813     mStreams[stream].mIndexMin = indexMin;
814     mStreams[stream].mIndexMax = indexMax;
815 }
816 
setStreamVolumeIndex(AudioSystem::stream_type stream,int index)817 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream, int index)
818 {
819 
820     if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
821         return BAD_VALUE;
822     }
823 
824     // Force max volume if stream cannot be muted
825     if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
826 
827     LOGV("setStreamVolumeIndex() stream %d, index %d", stream, index);
828     mStreams[stream].mIndexCur = index;
829 
830     // compute and apply stream volume on all outputs according to connected device
831     status_t status = NO_ERROR;
832     for (size_t i = 0; i < mOutputs.size(); i++) {
833         status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), mOutputs.valueAt(i)->device());
834         if (volStatus != NO_ERROR) {
835             status = volStatus;
836         }
837     }
838     return status;
839 }
840 
getStreamVolumeIndex(AudioSystem::stream_type stream,int * index)841 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream, int *index)
842 {
843     if (index == 0) {
844         return BAD_VALUE;
845     }
846     LOGV("getStreamVolumeIndex() stream %d", stream);
847     *index =  mStreams[stream].mIndexCur;
848     return NO_ERROR;
849 }
850 
getOutputForEffect(effect_descriptor_t * desc)851 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(effect_descriptor_t *desc)
852 {
853     LOGV("getOutputForEffect()");
854     // apply simple rule where global effects are attached to the same output as MUSIC streams
855     return getOutput(AudioSystem::MUSIC);
856 }
857 
registerEffect(effect_descriptor_t * desc,audio_io_handle_t io,uint32_t strategy,int session,int id)858 status_t AudioPolicyManagerBase::registerEffect(effect_descriptor_t *desc,
859                                 audio_io_handle_t io,
860                                 uint32_t strategy,
861                                 int session,
862                                 int id)
863 {
864     ssize_t index = mOutputs.indexOfKey(io);
865     if (index < 0) {
866         index = mInputs.indexOfKey(io);
867         if (index < 0) {
868             LOGW("registerEffect() unknown io %d", io);
869             return INVALID_OPERATION;
870         }
871     }
872 
873     if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
874         LOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
875                 desc->name, desc->memoryUsage);
876         return INVALID_OPERATION;
877     }
878     mTotalEffectsMemory += desc->memoryUsage;
879     LOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
880             desc->name, io, strategy, session, id);
881     LOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
882 
883     EffectDescriptor *pDesc = new EffectDescriptor();
884     memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
885     pDesc->mIo = io;
886     pDesc->mStrategy = (routing_strategy)strategy;
887     pDesc->mSession = session;
888     pDesc->mEnabled = false;
889 
890     mEffects.add(id, pDesc);
891 
892     return NO_ERROR;
893 }
894 
unregisterEffect(int id)895 status_t AudioPolicyManagerBase::unregisterEffect(int id)
896 {
897     ssize_t index = mEffects.indexOfKey(id);
898     if (index < 0) {
899         LOGW("unregisterEffect() unknown effect ID %d", id);
900         return INVALID_OPERATION;
901     }
902 
903     EffectDescriptor *pDesc = mEffects.valueAt(index);
904 
905     setEffectEnabled(pDesc, false);
906 
907     if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
908         LOGW("unregisterEffect() memory %d too big for total %d",
909                 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
910         pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
911     }
912     mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
913     LOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
914             pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
915 
916     mEffects.removeItem(id);
917     delete pDesc;
918 
919     return NO_ERROR;
920 }
921 
setEffectEnabled(int id,bool enabled)922 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
923 {
924     ssize_t index = mEffects.indexOfKey(id);
925     if (index < 0) {
926         LOGW("unregisterEffect() unknown effect ID %d", id);
927         return INVALID_OPERATION;
928     }
929 
930     return setEffectEnabled(mEffects.valueAt(index), enabled);
931 }
932 
setEffectEnabled(EffectDescriptor * pDesc,bool enabled)933 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
934 {
935     if (enabled == pDesc->mEnabled) {
936         LOGV("setEffectEnabled(%s) effect already %s",
937              enabled?"true":"false", enabled?"enabled":"disabled");
938         return INVALID_OPERATION;
939     }
940 
941     if (enabled) {
942         if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
943             LOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
944                  pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
945             return INVALID_OPERATION;
946         }
947         mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
948         LOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
949     } else {
950         if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
951             LOGW("setEffectEnabled(false) CPU load %d too high for total %d",
952                     pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
953             pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
954         }
955         mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
956         LOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
957     }
958     pDesc->mEnabled = enabled;
959     return NO_ERROR;
960 }
961 
isStreamActive(int stream,uint32_t inPastMs) const962 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
963 {
964     nsecs_t sysTime = systemTime();
965     for (size_t i = 0; i < mOutputs.size(); i++) {
966         if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
967             ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
968             return true;
969         }
970     }
971     return false;
972 }
973 
974 
dump(int fd)975 status_t AudioPolicyManagerBase::dump(int fd)
976 {
977     const size_t SIZE = 256;
978     char buffer[SIZE];
979     String8 result;
980 
981     snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
982     result.append(buffer);
983     snprintf(buffer, SIZE, " Hardware Output: %d\n", mHardwareOutput);
984     result.append(buffer);
985 #ifdef WITH_A2DP
986     snprintf(buffer, SIZE, " A2DP Output: %d\n", mA2dpOutput);
987     result.append(buffer);
988     snprintf(buffer, SIZE, " Duplicated Output: %d\n", mDuplicatedOutput);
989     result.append(buffer);
990     snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
991     result.append(buffer);
992 #endif
993     snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
994     result.append(buffer);
995     snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
996     result.append(buffer);
997     snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
998     result.append(buffer);
999     snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1000     result.append(buffer);
1001     snprintf(buffer, SIZE, " Ringer mode: %d\n", mRingerMode);
1002     result.append(buffer);
1003     snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1004     result.append(buffer);
1005     snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1006     result.append(buffer);
1007     snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1008     result.append(buffer);
1009     snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1010     result.append(buffer);
1011     write(fd, result.string(), result.size());
1012 
1013     snprintf(buffer, SIZE, "\nOutputs dump:\n");
1014     write(fd, buffer, strlen(buffer));
1015     for (size_t i = 0; i < mOutputs.size(); i++) {
1016         snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1017         write(fd, buffer, strlen(buffer));
1018         mOutputs.valueAt(i)->dump(fd);
1019     }
1020 
1021     snprintf(buffer, SIZE, "\nInputs dump:\n");
1022     write(fd, buffer, strlen(buffer));
1023     for (size_t i = 0; i < mInputs.size(); i++) {
1024         snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1025         write(fd, buffer, strlen(buffer));
1026         mInputs.valueAt(i)->dump(fd);
1027     }
1028 
1029     snprintf(buffer, SIZE, "\nStreams dump:\n");
1030     write(fd, buffer, strlen(buffer));
1031     snprintf(buffer, SIZE, " Stream  Index Min  Index Max  Index Cur  Can be muted\n");
1032     write(fd, buffer, strlen(buffer));
1033     for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1034         snprintf(buffer, SIZE, " %02d", i);
1035         mStreams[i].dump(buffer + 3, SIZE);
1036         write(fd, buffer, strlen(buffer));
1037     }
1038 
1039     snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1040             (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1041     write(fd, buffer, strlen(buffer));
1042 
1043     snprintf(buffer, SIZE, "Registered effects:\n");
1044     write(fd, buffer, strlen(buffer));
1045     for (size_t i = 0; i < mEffects.size(); i++) {
1046         snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1047         write(fd, buffer, strlen(buffer));
1048         mEffects.valueAt(i)->dump(fd);
1049     }
1050 
1051 
1052     return NO_ERROR;
1053 }
1054 
1055 // ----------------------------------------------------------------------------
1056 // AudioPolicyManagerBase
1057 // ----------------------------------------------------------------------------
1058 
AudioPolicyManagerBase(AudioPolicyClientInterface * clientInterface)1059 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1060     :
1061 #ifdef AUDIO_POLICY_TEST
1062     Thread(false),
1063 #endif //AUDIO_POLICY_TEST
1064     mPhoneState(AudioSystem::MODE_NORMAL), mRingerMode(0),
1065     mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1066     mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1067     mA2dpSuspended(false)
1068 {
1069     mpClientInterface = clientInterface;
1070 
1071     for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1072         mForceUse[i] = AudioSystem::FORCE_NONE;
1073     }
1074 
1075     initializeVolumeCurves();
1076 
1077     // devices available by default are speaker, ear piece and microphone
1078     mAvailableOutputDevices = AudioSystem::DEVICE_OUT_EARPIECE |
1079                         AudioSystem::DEVICE_OUT_SPEAKER;
1080     mAvailableInputDevices = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1081 
1082 #ifdef WITH_A2DP
1083     mA2dpOutput = 0;
1084     mDuplicatedOutput = 0;
1085     mA2dpDeviceAddress = String8("");
1086 #endif
1087     mScoDeviceAddress = String8("");
1088 
1089     // open hardware output
1090     AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1091     outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1092     mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1093                                     &outputDesc->mSamplingRate,
1094                                     &outputDesc->mFormat,
1095                                     &outputDesc->mChannels,
1096                                     &outputDesc->mLatency,
1097                                     outputDesc->mFlags);
1098 
1099     if (mHardwareOutput == 0) {
1100         LOGE("Failed to initialize hardware output stream, samplingRate: %d, format %d, channels %d",
1101                 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1102     } else {
1103         addOutput(mHardwareOutput, outputDesc);
1104         setOutputDevice(mHardwareOutput, (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER, true);
1105         //TODO: configure audio effect output stage here
1106     }
1107 
1108     updateDeviceForStrategy();
1109 #ifdef AUDIO_POLICY_TEST
1110     if (mHardwareOutput != 0) {
1111         AudioParameter outputCmd = AudioParameter();
1112         outputCmd.addInt(String8("set_id"), 0);
1113         mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
1114 
1115         mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
1116         mTestSamplingRate = 44100;
1117         mTestFormat = AudioSystem::PCM_16_BIT;
1118         mTestChannels =  AudioSystem::CHANNEL_OUT_STEREO;
1119         mTestLatencyMs = 0;
1120         mCurOutput = 0;
1121         mDirectOutput = false;
1122         for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1123             mTestOutputs[i] = 0;
1124         }
1125 
1126         const size_t SIZE = 256;
1127         char buffer[SIZE];
1128         snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1129         run(buffer, ANDROID_PRIORITY_AUDIO);
1130     }
1131 #endif //AUDIO_POLICY_TEST
1132 }
1133 
~AudioPolicyManagerBase()1134 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1135 {
1136 #ifdef AUDIO_POLICY_TEST
1137     exit();
1138 #endif //AUDIO_POLICY_TEST
1139    for (size_t i = 0; i < mOutputs.size(); i++) {
1140         mpClientInterface->closeOutput(mOutputs.keyAt(i));
1141         delete mOutputs.valueAt(i);
1142    }
1143    mOutputs.clear();
1144    for (size_t i = 0; i < mInputs.size(); i++) {
1145         mpClientInterface->closeInput(mInputs.keyAt(i));
1146         delete mInputs.valueAt(i);
1147    }
1148    mInputs.clear();
1149 }
1150 
initCheck()1151 status_t AudioPolicyManagerBase::initCheck()
1152 {
1153     return (mHardwareOutput == 0) ? NO_INIT : NO_ERROR;
1154 }
1155 
1156 #ifdef AUDIO_POLICY_TEST
threadLoop()1157 bool AudioPolicyManagerBase::threadLoop()
1158 {
1159     LOGV("entering threadLoop()");
1160     while (!exitPending())
1161     {
1162         String8 command;
1163         int valueInt;
1164         String8 value;
1165 
1166         Mutex::Autolock _l(mLock);
1167         mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1168 
1169         command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1170         AudioParameter param = AudioParameter(command);
1171 
1172         if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1173             valueInt != 0) {
1174             LOGV("Test command %s received", command.string());
1175             String8 target;
1176             if (param.get(String8("target"), target) != NO_ERROR) {
1177                 target = "Manager";
1178             }
1179             if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1180                 param.remove(String8("test_cmd_policy_output"));
1181                 mCurOutput = valueInt;
1182             }
1183             if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1184                 param.remove(String8("test_cmd_policy_direct"));
1185                 if (value == "false") {
1186                     mDirectOutput = false;
1187                 } else if (value == "true") {
1188                     mDirectOutput = true;
1189                 }
1190             }
1191             if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1192                 param.remove(String8("test_cmd_policy_input"));
1193                 mTestInput = valueInt;
1194             }
1195 
1196             if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1197                 param.remove(String8("test_cmd_policy_format"));
1198                 int format = AudioSystem::INVALID_FORMAT;
1199                 if (value == "PCM 16 bits") {
1200                     format = AudioSystem::PCM_16_BIT;
1201                 } else if (value == "PCM 8 bits") {
1202                     format = AudioSystem::PCM_8_BIT;
1203                 } else if (value == "Compressed MP3") {
1204                     format = AudioSystem::MP3;
1205                 }
1206                 if (format != AudioSystem::INVALID_FORMAT) {
1207                     if (target == "Manager") {
1208                         mTestFormat = format;
1209                     } else if (mTestOutputs[mCurOutput] != 0) {
1210                         AudioParameter outputParam = AudioParameter();
1211                         outputParam.addInt(String8("format"), format);
1212                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1213                     }
1214                 }
1215             }
1216             if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1217                 param.remove(String8("test_cmd_policy_channels"));
1218                 int channels = 0;
1219 
1220                 if (value == "Channels Stereo") {
1221                     channels =  AudioSystem::CHANNEL_OUT_STEREO;
1222                 } else if (value == "Channels Mono") {
1223                     channels =  AudioSystem::CHANNEL_OUT_MONO;
1224                 }
1225                 if (channels != 0) {
1226                     if (target == "Manager") {
1227                         mTestChannels = channels;
1228                     } else if (mTestOutputs[mCurOutput] != 0) {
1229                         AudioParameter outputParam = AudioParameter();
1230                         outputParam.addInt(String8("channels"), channels);
1231                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1232                     }
1233                 }
1234             }
1235             if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1236                 param.remove(String8("test_cmd_policy_sampleRate"));
1237                 if (valueInt >= 0 && valueInt <= 96000) {
1238                     int samplingRate = valueInt;
1239                     if (target == "Manager") {
1240                         mTestSamplingRate = samplingRate;
1241                     } else if (mTestOutputs[mCurOutput] != 0) {
1242                         AudioParameter outputParam = AudioParameter();
1243                         outputParam.addInt(String8("sampling_rate"), samplingRate);
1244                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1245                     }
1246                 }
1247             }
1248 
1249             if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1250                 param.remove(String8("test_cmd_policy_reopen"));
1251 
1252                 mpClientInterface->closeOutput(mHardwareOutput);
1253                 delete mOutputs.valueFor(mHardwareOutput);
1254                 mOutputs.removeItem(mHardwareOutput);
1255 
1256                 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1257                 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1258                 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1259                                                 &outputDesc->mSamplingRate,
1260                                                 &outputDesc->mFormat,
1261                                                 &outputDesc->mChannels,
1262                                                 &outputDesc->mLatency,
1263                                                 outputDesc->mFlags);
1264                 if (mHardwareOutput == 0) {
1265                     LOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1266                             outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1267                 } else {
1268                     AudioParameter outputCmd = AudioParameter();
1269                     outputCmd.addInt(String8("set_id"), 0);
1270                     mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
1271                     addOutput(mHardwareOutput, outputDesc);
1272                 }
1273             }
1274 
1275 
1276             mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1277         }
1278     }
1279     return false;
1280 }
1281 
exit()1282 void AudioPolicyManagerBase::exit()
1283 {
1284     {
1285         AutoMutex _l(mLock);
1286         requestExit();
1287         mWaitWorkCV.signal();
1288     }
1289     requestExitAndWait();
1290 }
1291 
testOutputIndex(audio_io_handle_t output)1292 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1293 {
1294     for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1295         if (output == mTestOutputs[i]) return i;
1296     }
1297     return 0;
1298 }
1299 #endif //AUDIO_POLICY_TEST
1300 
1301 // ---
1302 
addOutput(audio_io_handle_t id,AudioOutputDescriptor * outputDesc)1303 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1304 {
1305     outputDesc->mId = id;
1306     mOutputs.add(id, outputDesc);
1307 }
1308 
1309 
1310 #ifdef WITH_A2DP
handleA2dpConnection(AudioSystem::audio_devices device,const char * device_address)1311 status_t AudioPolicyManagerBase::handleA2dpConnection(AudioSystem::audio_devices device,
1312                                                  const char *device_address)
1313 {
1314     // when an A2DP device is connected, open an A2DP and a duplicated output
1315     LOGV("opening A2DP output for device %s", device_address);
1316     AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1317     outputDesc->mDevice = device;
1318     mA2dpOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1319                                             &outputDesc->mSamplingRate,
1320                                             &outputDesc->mFormat,
1321                                             &outputDesc->mChannels,
1322                                             &outputDesc->mLatency,
1323                                             outputDesc->mFlags);
1324     if (mA2dpOutput) {
1325         // add A2DP output descriptor
1326         addOutput(mA2dpOutput, outputDesc);
1327 
1328         //TODO: configure audio effect output stage here
1329 
1330         // set initial stream volume for A2DP device
1331         applyStreamVolumes(mA2dpOutput, device);
1332         if (a2dpUsedForSonification()) {
1333             mDuplicatedOutput = mpClientInterface->openDuplicateOutput(mA2dpOutput, mHardwareOutput);
1334         }
1335         if (mDuplicatedOutput != 0 ||
1336             !a2dpUsedForSonification()) {
1337             // If both A2DP and duplicated outputs are open, send device address to A2DP hardware
1338             // interface
1339             AudioParameter param;
1340             param.add(String8("a2dp_sink_address"), String8(device_address));
1341             mpClientInterface->setParameters(mA2dpOutput, param.toString());
1342             mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
1343 
1344             if (a2dpUsedForSonification()) {
1345                 // add duplicated output descriptor
1346                 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor();
1347                 dupOutputDesc->mOutput1 = mOutputs.valueFor(mHardwareOutput);
1348                 dupOutputDesc->mOutput2 = mOutputs.valueFor(mA2dpOutput);
1349                 dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate;
1350                 dupOutputDesc->mFormat = outputDesc->mFormat;
1351                 dupOutputDesc->mChannels = outputDesc->mChannels;
1352                 dupOutputDesc->mLatency = outputDesc->mLatency;
1353                 addOutput(mDuplicatedOutput, dupOutputDesc);
1354                 applyStreamVolumes(mDuplicatedOutput, device);
1355             }
1356         } else {
1357             LOGW("getOutput() could not open duplicated output for %d and %d",
1358                     mHardwareOutput, mA2dpOutput);
1359             mpClientInterface->closeOutput(mA2dpOutput);
1360             mOutputs.removeItem(mA2dpOutput);
1361             mA2dpOutput = 0;
1362             delete outputDesc;
1363             return NO_INIT;
1364         }
1365     } else {
1366         LOGW("setDeviceConnectionState() could not open A2DP output for device %x", device);
1367         delete outputDesc;
1368         return NO_INIT;
1369     }
1370     AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1371 
1372     if (!a2dpUsedForSonification()) {
1373         // mute music on A2DP output if a notification or ringtone is playing
1374         uint32_t refCount = hwOutputDesc->strategyRefCount(STRATEGY_SONIFICATION);
1375         refCount += hwOutputDesc->strategyRefCount(STRATEGY_ENFORCED_AUDIBLE);
1376         for (uint32_t i = 0; i < refCount; i++) {
1377             setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
1378         }
1379     }
1380 
1381     mA2dpSuspended = false;
1382 
1383     return NO_ERROR;
1384 }
1385 
handleA2dpDisconnection(AudioSystem::audio_devices device,const char * device_address)1386 status_t AudioPolicyManagerBase::handleA2dpDisconnection(AudioSystem::audio_devices device,
1387                                                     const char *device_address)
1388 {
1389     if (mA2dpOutput == 0) {
1390         LOGW("setDeviceConnectionState() disconnecting A2DP and no A2DP output!");
1391         return INVALID_OPERATION;
1392     }
1393 
1394     if (mA2dpDeviceAddress != device_address) {
1395         LOGW("setDeviceConnectionState() disconnecting unknow A2DP sink address %s", device_address);
1396         return INVALID_OPERATION;
1397     }
1398 
1399     // mute media strategy to avoid outputting sound on hardware output while music stream
1400     // is switched from A2DP output and before music is paused by music application
1401     setStrategyMute(STRATEGY_MEDIA, true, mHardwareOutput);
1402     setStrategyMute(STRATEGY_MEDIA, false, mHardwareOutput, MUTE_TIME_MS);
1403 
1404     if (!a2dpUsedForSonification()) {
1405         // unmute music on A2DP output if a notification or ringtone is playing
1406         uint32_t refCount = mOutputs.valueFor(mHardwareOutput)->strategyRefCount(STRATEGY_SONIFICATION);
1407         refCount += mOutputs.valueFor(mHardwareOutput)->strategyRefCount(STRATEGY_ENFORCED_AUDIBLE);
1408         for (uint32_t i = 0; i < refCount; i++) {
1409             setStrategyMute(STRATEGY_MEDIA, false, mA2dpOutput);
1410         }
1411     }
1412     mA2dpDeviceAddress = "";
1413     mA2dpSuspended = false;
1414     return NO_ERROR;
1415 }
1416 
closeA2dpOutputs()1417 void AudioPolicyManagerBase::closeA2dpOutputs()
1418 {
1419 
1420     LOGV("setDeviceConnectionState() closing A2DP and duplicated output!");
1421 
1422     if (mDuplicatedOutput != 0) {
1423         AudioOutputDescriptor *dupOutputDesc = mOutputs.valueFor(mDuplicatedOutput);
1424         AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1425         // As all active tracks on duplicated output will be deleted,
1426         // and as they were also referenced on hardware output, the reference
1427         // count for their stream type must be adjusted accordingly on
1428         // hardware output.
1429         for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1430             int refCount = dupOutputDesc->mRefCount[i];
1431             hwOutputDesc->changeRefCount((AudioSystem::stream_type)i,-refCount);
1432         }
1433 
1434         mpClientInterface->closeOutput(mDuplicatedOutput);
1435         delete mOutputs.valueFor(mDuplicatedOutput);
1436         mOutputs.removeItem(mDuplicatedOutput);
1437         mDuplicatedOutput = 0;
1438     }
1439     if (mA2dpOutput != 0) {
1440         AudioParameter param;
1441         param.add(String8("closing"), String8("true"));
1442         mpClientInterface->setParameters(mA2dpOutput, param.toString());
1443 
1444         mpClientInterface->closeOutput(mA2dpOutput);
1445         delete mOutputs.valueFor(mA2dpOutput);
1446         mOutputs.removeItem(mA2dpOutput);
1447         mA2dpOutput = 0;
1448     }
1449 }
1450 
checkOutputForStrategy(routing_strategy strategy)1451 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
1452 {
1453     uint32_t prevDevice = getDeviceForStrategy(strategy);
1454     uint32_t curDevice = getDeviceForStrategy(strategy, false);
1455     bool a2dpWasUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(prevDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
1456     bool a2dpIsUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(curDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
1457     audio_io_handle_t srcOutput = 0;
1458     audio_io_handle_t dstOutput = 0;
1459 
1460     if (a2dpWasUsed && !a2dpIsUsed) {
1461         bool dupUsed = a2dpUsedForSonification() && a2dpWasUsed && (AudioSystem::popCount(prevDevice) == 2);
1462         dstOutput = mHardwareOutput;
1463         if (dupUsed) {
1464             LOGV("checkOutputForStrategy() moving strategy %d from duplicated", strategy);
1465             srcOutput = mDuplicatedOutput;
1466         } else {
1467             LOGV("checkOutputForStrategy() moving strategy %d from a2dp", strategy);
1468             srcOutput = mA2dpOutput;
1469         }
1470     }
1471     if (a2dpIsUsed && !a2dpWasUsed) {
1472         bool dupUsed = a2dpUsedForSonification() && a2dpIsUsed && (AudioSystem::popCount(curDevice) == 2);
1473         srcOutput = mHardwareOutput;
1474         if (dupUsed) {
1475             LOGV("checkOutputForStrategy() moving strategy %d to duplicated", strategy);
1476             dstOutput = mDuplicatedOutput;
1477         } else {
1478             LOGV("checkOutputForStrategy() moving strategy %d to a2dp", strategy);
1479             dstOutput = mA2dpOutput;
1480         }
1481     }
1482 
1483     if (srcOutput != 0 && dstOutput != 0) {
1484         // Move effects associated to this strategy from previous output to new output
1485         for (size_t i = 0; i < mEffects.size(); i++) {
1486             EffectDescriptor *desc = mEffects.valueAt(i);
1487             if (desc->mSession != AudioSystem::SESSION_OUTPUT_STAGE &&
1488                     desc->mStrategy == strategy &&
1489                     desc->mIo == srcOutput) {
1490                 LOGV("checkOutputForStrategy() moving effect %d to output %d", mEffects.keyAt(i), dstOutput);
1491                 mpClientInterface->moveEffects(desc->mSession, srcOutput, dstOutput);
1492                 desc->mIo = dstOutput;
1493             }
1494         }
1495         // Move tracks associated to this strategy from previous output to new output
1496         for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1497             if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1498                 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, dstOutput);
1499             }
1500         }
1501     }
1502 }
1503 
checkOutputForAllStrategies()1504 void AudioPolicyManagerBase::checkOutputForAllStrategies()
1505 {
1506     checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
1507     checkOutputForStrategy(STRATEGY_PHONE);
1508     checkOutputForStrategy(STRATEGY_SONIFICATION);
1509     checkOutputForStrategy(STRATEGY_MEDIA);
1510     checkOutputForStrategy(STRATEGY_DTMF);
1511 }
1512 
checkA2dpSuspend()1513 void AudioPolicyManagerBase::checkA2dpSuspend()
1514 {
1515     // suspend A2DP output if:
1516     //      (NOT already suspended) &&
1517     //      ((SCO device is connected &&
1518     //       (forced usage for communication || for record is SCO))) ||
1519     //      (phone state is ringing || in call)
1520     //
1521     // restore A2DP output if:
1522     //      (Already suspended) &&
1523     //      ((SCO device is NOT connected ||
1524     //       (forced usage NOT for communication && NOT for record is SCO))) &&
1525     //      (phone state is NOT ringing && NOT in call)
1526     //
1527     if (mA2dpOutput == 0) {
1528         return;
1529     }
1530 
1531     if (mA2dpSuspended) {
1532         if (((mScoDeviceAddress == "") ||
1533              ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1534               (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1535              ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1536               (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1537 
1538             mpClientInterface->restoreOutput(mA2dpOutput);
1539             mA2dpSuspended = false;
1540         }
1541     } else {
1542         if (((mScoDeviceAddress != "") &&
1543              ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1544               (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1545              ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1546               (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1547 
1548             mpClientInterface->suspendOutput(mA2dpOutput);
1549             mA2dpSuspended = true;
1550         }
1551     }
1552 }
1553 
1554 
1555 #endif
1556 
getNewDevice(audio_io_handle_t output,bool fromCache)1557 uint32_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1558 {
1559     uint32_t device = 0;
1560 
1561     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1562     // check the following by order of priority to request a routing change if necessary:
1563     // 1: the strategy enforced audible is active on the output:
1564     //      use device for strategy enforced audible
1565     // 2: we are in call or the strategy phone is active on the output:
1566     //      use device for strategy phone
1567     // 3: the strategy sonification is active on the output:
1568     //      use device for strategy sonification
1569     // 4: the strategy media is active on the output:
1570     //      use device for strategy media
1571     // 5: the strategy DTMF is active on the output:
1572     //      use device for strategy DTMF
1573     if (outputDesc->isUsedByStrategy(STRATEGY_ENFORCED_AUDIBLE)) {
1574         device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
1575     } else if (isInCall() ||
1576                     outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1577         device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1578     } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1579         device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1580     } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1581         device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1582     } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1583         device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1584     }
1585 
1586     LOGV("getNewDevice() selected device %x", device);
1587     return device;
1588 }
1589 
getStrategyForStream(AudioSystem::stream_type stream)1590 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
1591     return (uint32_t)getStrategy(stream);
1592 }
1593 
getDevicesForStream(AudioSystem::stream_type stream)1594 uint32_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
1595     uint32_t devices;
1596     // By checking the range of stream before calling getStrategy, we avoid
1597     // getStrategy's behavior for invalid streams.  getStrategy would do a LOGE
1598     // and then return STRATEGY_MEDIA, but we want to return the empty set.
1599     if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
1600         devices = 0;
1601     } else {
1602         AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
1603         devices = getDeviceForStrategy(strategy, true);
1604     }
1605     return devices;
1606 }
1607 
getStrategy(AudioSystem::stream_type stream)1608 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
1609         AudioSystem::stream_type stream) {
1610     // stream to strategy mapping
1611     switch (stream) {
1612     case AudioSystem::VOICE_CALL:
1613     case AudioSystem::BLUETOOTH_SCO:
1614         return STRATEGY_PHONE;
1615     case AudioSystem::RING:
1616     case AudioSystem::NOTIFICATION:
1617     case AudioSystem::ALARM:
1618         return STRATEGY_SONIFICATION;
1619     case AudioSystem::DTMF:
1620         return STRATEGY_DTMF;
1621     default:
1622         LOGE("unknown stream type");
1623     case AudioSystem::SYSTEM:
1624         // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1625         // while key clicks are played produces a poor result
1626     case AudioSystem::TTS:
1627     case AudioSystem::MUSIC:
1628         return STRATEGY_MEDIA;
1629     case AudioSystem::ENFORCED_AUDIBLE:
1630         return STRATEGY_ENFORCED_AUDIBLE;
1631     }
1632 }
1633 
getDeviceForStrategy(routing_strategy strategy,bool fromCache)1634 uint32_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy, bool fromCache)
1635 {
1636     uint32_t device = 0;
1637 
1638     if (fromCache) {
1639         LOGV("getDeviceForStrategy() from cache strategy %d, device %x", strategy, mDeviceForStrategy[strategy]);
1640         return mDeviceForStrategy[strategy];
1641     }
1642 
1643     switch (strategy) {
1644     case STRATEGY_DTMF:
1645         if (!isInCall()) {
1646             // when off call, DTMF strategy follows the same rules as MEDIA strategy
1647             device = getDeviceForStrategy(STRATEGY_MEDIA, false);
1648             break;
1649         }
1650         // when in call, DTMF and PHONE strategies follow the same rules
1651         // FALL THROUGH
1652 
1653     case STRATEGY_PHONE:
1654         // for phone strategy, we first consider the forced use and then the available devices by order
1655         // of priority
1656         switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
1657         case AudioSystem::FORCE_BT_SCO:
1658             if (!isInCall() || strategy != STRATEGY_DTMF) {
1659                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1660                 if (device) break;
1661             }
1662             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
1663             if (device) break;
1664             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
1665             if (device) break;
1666             // if SCO device is requested but no SCO device is available, fall back to default case
1667             // FALL THROUGH
1668 
1669         default:    // FORCE_NONE
1670             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1671             if (device) break;
1672             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1673             if (device) break;
1674 #ifdef WITH_A2DP
1675             // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
1676             if (!isInCall() && !mA2dpSuspended) {
1677                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1678                 if (device) break;
1679                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1680                 if (device) break;
1681             }
1682 #endif
1683             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1684             if (device) break;
1685             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1686             if (device) break;
1687             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1688             if (device) break;
1689             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
1690             if (device == 0) {
1691                 LOGE("getDeviceForStrategy() earpiece device not found");
1692             }
1693             break;
1694 
1695         case AudioSystem::FORCE_SPEAKER:
1696 #ifdef WITH_A2DP
1697             // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
1698             // A2DP speaker when forcing to speaker output
1699             if (!isInCall() && !mA2dpSuspended) {
1700                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1701                 if (device) break;
1702             }
1703 #endif
1704             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1705             if (device) break;
1706             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1707             if (device) break;
1708             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1709             if (device) break;
1710             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1711             if (device == 0) {
1712                 LOGE("getDeviceForStrategy() speaker device not found");
1713             }
1714             break;
1715         }
1716     break;
1717 
1718     case STRATEGY_SONIFICATION:
1719 
1720         // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
1721         // handleIncallSonification().
1722         if (isInCall()) {
1723             device = getDeviceForStrategy(STRATEGY_PHONE, false);
1724             break;
1725         }
1726         // FALL THROUGH
1727 
1728     case STRATEGY_ENFORCED_AUDIBLE:
1729         // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
1730         // except when in call where it doesn't default to STRATEGY_PHONE behavior
1731 
1732         device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1733         if (device == 0) {
1734             LOGE("getDeviceForStrategy() speaker device not found");
1735         }
1736         // The second device used for sonification is the same as the device used by media strategy
1737         // FALL THROUGH
1738 
1739     case STRATEGY_MEDIA: {
1740         uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1741         if (device2 == 0) {
1742             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1743         }
1744 #ifdef WITH_A2DP
1745         if ((mA2dpOutput != 0) && !mA2dpSuspended &&
1746                 (strategy == STRATEGY_MEDIA || a2dpUsedForSonification())) {
1747             if (device2 == 0) {
1748                 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1749             }
1750             if (device2 == 0) {
1751                 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1752             }
1753             if (device2 == 0) {
1754                 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1755             }
1756         }
1757 #endif
1758         if (device2 == 0) {
1759             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1760         }
1761         if (device2 == 0) {
1762             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1763         }
1764         if (device2 == 0) {
1765             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1766         }
1767         if (device2 == 0) {
1768             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1769         }
1770 
1771         // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
1772         // STRATEGY_ENFORCED_AUDIBLE, 0 otherwise
1773         device |= device2;
1774         if (device == 0) {
1775             LOGE("getDeviceForStrategy() speaker device not found");
1776         }
1777         } break;
1778 
1779     default:
1780         LOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
1781         break;
1782     }
1783 
1784     LOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
1785     return device;
1786 }
1787 
updateDeviceForStrategy()1788 void AudioPolicyManagerBase::updateDeviceForStrategy()
1789 {
1790     for (int i = 0; i < NUM_STRATEGIES; i++) {
1791         mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false);
1792     }
1793 }
1794 
setOutputDevice(audio_io_handle_t output,uint32_t device,bool force,int delayMs)1795 void AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output, uint32_t device, bool force, int delayMs)
1796 {
1797     LOGV("setOutputDevice() output %d device %x delayMs %d", output, device, delayMs);
1798     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1799 
1800 
1801     if (outputDesc->isDuplicated()) {
1802         setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
1803         setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
1804         return;
1805     }
1806 #ifdef WITH_A2DP
1807     // filter devices according to output selected
1808     if (output == mA2dpOutput) {
1809         device &= AudioSystem::DEVICE_OUT_ALL_A2DP;
1810     } else {
1811         device &= ~AudioSystem::DEVICE_OUT_ALL_A2DP;
1812     }
1813 #endif
1814 
1815     uint32_t prevDevice = (uint32_t)outputDesc->device();
1816     // Do not change the routing if:
1817     //  - the requestede device is 0
1818     //  - the requested device is the same as current device and force is not specified.
1819     // Doing this check here allows the caller to call setOutputDevice() without conditions
1820     if ((device == 0 || device == prevDevice) && !force) {
1821         LOGV("setOutputDevice() setting same device %x or null device for output %d", device, output);
1822         return;
1823     }
1824 
1825     outputDesc->mDevice = device;
1826     // mute media streams if both speaker and headset are selected
1827     if (output == mHardwareOutput && AudioSystem::popCount(device) == 2) {
1828         setStrategyMute(STRATEGY_MEDIA, true, output);
1829         // wait for the PCM output buffers to empty before proceeding with the rest of the command
1830         // FIXME: increased delay due to larger buffers used for low power audio mode.
1831         // remove when low power audio is controlled by policy manager.
1832         usleep(outputDesc->mLatency*8*1000);
1833     }
1834 
1835     // do the routing
1836     AudioParameter param = AudioParameter();
1837     param.addInt(String8(AudioParameter::keyRouting), (int)device);
1838     mpClientInterface->setParameters(mHardwareOutput, param.toString(), delayMs);
1839     // update stream volumes according to new device
1840     applyStreamVolumes(output, device, delayMs);
1841 
1842     // if changing from a combined headset + speaker route, unmute media streams
1843     if (output == mHardwareOutput && AudioSystem::popCount(prevDevice) == 2) {
1844         setStrategyMute(STRATEGY_MEDIA, false, output, delayMs);
1845     }
1846 }
1847 
getDeviceForInputSource(int inputSource)1848 uint32_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
1849 {
1850     uint32_t device;
1851 
1852     switch(inputSource) {
1853     case AUDIO_SOURCE_DEFAULT:
1854     case AUDIO_SOURCE_MIC:
1855     case AUDIO_SOURCE_VOICE_RECOGNITION:
1856     case AUDIO_SOURCE_VOICE_COMMUNICATION:
1857         if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
1858             mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
1859             device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
1860         } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
1861             device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
1862         } else {
1863             device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1864         }
1865         break;
1866     case AUDIO_SOURCE_CAMCORDER:
1867         if (hasBackMicrophone()) {
1868             device = AudioSystem::DEVICE_IN_BACK_MIC;
1869         } else {
1870             device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1871         }
1872         break;
1873     case AUDIO_SOURCE_VOICE_UPLINK:
1874     case AUDIO_SOURCE_VOICE_DOWNLINK:
1875     case AUDIO_SOURCE_VOICE_CALL:
1876         device = AudioSystem::DEVICE_IN_VOICE_CALL;
1877         break;
1878     default:
1879         LOGW("getDeviceForInputSource() invalid input source %d", inputSource);
1880         device = 0;
1881         break;
1882     }
1883     LOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
1884     return device;
1885 }
1886 
getActiveInput()1887 audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
1888 {
1889     for (size_t i = 0; i < mInputs.size(); i++) {
1890         if (mInputs.valueAt(i)->mRefCount > 0) {
1891             return mInputs.keyAt(i);
1892         }
1893     }
1894     return 0;
1895 }
1896 
1897 
getDeviceCategory(uint32_t device)1898 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(uint32_t device)
1899 {
1900     if (device == 0) {
1901         // this happens when forcing a route update and no track is active on an output.
1902         // In this case the returned category is not important.
1903         return DEVICE_CATEGORY_SPEAKER;
1904     }
1905 
1906     if (AudioSystem::popCount(device) > 1) {
1907         // Multiple device selection is either:
1908         //  - speaker + one other device: give priority to speaker in this case.
1909         //  - one A2DP device + another device: happens with duplicated output. In this case
1910         // retain the device on the A2DP output as the other must not correspond to an active
1911         // selection if not the speaker.
1912         if (device & AUDIO_DEVICE_OUT_SPEAKER)
1913             return DEVICE_CATEGORY_SPEAKER;
1914 
1915         device &= AUDIO_DEVICE_OUT_ALL_A2DP;
1916     }
1917 
1918     LOGW_IF(AudioSystem::popCount(device) != 1,
1919             "getDeviceCategory() invalid device combination: %08x",
1920             device);
1921 
1922     switch(device) {
1923         case AUDIO_DEVICE_OUT_EARPIECE:
1924             return DEVICE_CATEGORY_EARPIECE;
1925         case AUDIO_DEVICE_OUT_WIRED_HEADSET:
1926         case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
1927         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
1928         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
1929         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
1930         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
1931             return DEVICE_CATEGORY_HEADSET;
1932         case AUDIO_DEVICE_OUT_SPEAKER:
1933         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
1934         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
1935         default:
1936             return DEVICE_CATEGORY_SPEAKER;
1937     }
1938 }
1939 
volIndexToAmpl(uint32_t device,const StreamDescriptor & streamDesc,int indexInUi)1940 float AudioPolicyManagerBase::volIndexToAmpl(uint32_t device, const StreamDescriptor& streamDesc,
1941         int indexInUi)
1942 {
1943     device_category deviceCategory = getDeviceCategory(device);
1944     const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
1945 
1946     // the volume index in the UI is relative to the min and max volume indices for this stream type
1947     int nbSteps = 1 + curve[VOLMAX].mIndex -
1948             curve[VOLMIN].mIndex;
1949     int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
1950             (streamDesc.mIndexMax - streamDesc.mIndexMin);
1951 
1952     // find what part of the curve this index volume belongs to, or if it's out of bounds
1953     int segment = 0;
1954     if (volIdx < curve[VOLMIN].mIndex) {         // out of bounds
1955         return 0.0f;
1956     } else if (volIdx < curve[VOLKNEE1].mIndex) {
1957         segment = 0;
1958     } else if (volIdx < curve[VOLKNEE2].mIndex) {
1959         segment = 1;
1960     } else if (volIdx <= curve[VOLMAX].mIndex) {
1961         segment = 2;
1962     } else {                                                               // out of bounds
1963         return 1.0f;
1964     }
1965 
1966     // linear interpolation in the attenuation table in dB
1967     float decibels = curve[segment].mDBAttenuation +
1968             ((float)(volIdx - curve[segment].mIndex)) *
1969                 ( (curve[segment+1].mDBAttenuation -
1970                         curve[segment].mDBAttenuation) /
1971                     ((float)(curve[segment+1].mIndex -
1972                             curve[segment].mIndex)) );
1973 
1974     float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
1975 
1976     LOGV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
1977             curve[segment].mIndex, volIdx,
1978             curve[segment+1].mIndex,
1979             curve[segment].mDBAttenuation,
1980             decibels,
1981             curve[segment+1].mDBAttenuation,
1982             amplification);
1983 
1984     return amplification;
1985 }
1986 
1987 const AudioPolicyManagerBase::VolumeCurvePoint
1988     AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
1989     {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
1990 };
1991 
1992 const AudioPolicyManagerBase::VolumeCurvePoint
1993     AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
1994     {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
1995 };
1996 
1997 const AudioPolicyManagerBase::VolumeCurvePoint
1998     AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
1999     {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2000 };
2001 
2002 const AudioPolicyManagerBase::VolumeCurvePoint
2003     AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2004     {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2005 };
2006 
2007 
2008 const AudioPolicyManagerBase::VolumeCurvePoint
2009             *AudioPolicyManagerBase::sVolumeProfiles[AudioPolicyManagerBase::NUM_STRATEGIES]
2010                                                    [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2011     { // STRATEGY_MEDIA
2012         sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2013         sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2014         sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2015     },
2016     { // STRATEGY_PHONE
2017         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2018         sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2019         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2020     },
2021     { // STRATEGY_SONIFICATION
2022         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2023         sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2024         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2025     },
2026     {  // STRATEGY_DTMF
2027         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2028         sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2029         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2030     },
2031     { // STRATEGY_ENFORCED_AUDIBLE
2032         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2033         sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2034         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2035     },
2036 };
2037 
initializeVolumeCurves()2038 void AudioPolicyManagerBase::initializeVolumeCurves()
2039 {
2040     for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2041         for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2042             mStreams[i].mVolumeCurve[j] =
2043                     sVolumeProfiles[getStrategy((AudioSystem::stream_type)i)][j];
2044         }
2045     }
2046 }
2047 
computeVolume(int stream,int index,audio_io_handle_t output,uint32_t device)2048 float AudioPolicyManagerBase::computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device)
2049 {
2050     float volume = 1.0;
2051     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2052     StreamDescriptor &streamDesc = mStreams[stream];
2053 
2054     if (device == 0) {
2055         device = outputDesc->device();
2056     }
2057 
2058     // if volume is not 0 (not muted), force media volume to max on digital output
2059     if (stream == AudioSystem::MUSIC &&
2060         index != mStreams[stream].mIndexMin &&
2061         (device == AudioSystem::DEVICE_OUT_AUX_DIGITAL ||
2062         device == AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET)) {
2063         return 1.0;
2064     }
2065 
2066     volume = volIndexToAmpl(device, streamDesc, index);
2067 
2068     // if a headset is connected, apply the following rules to ring tones and notifications
2069     // to avoid sound level bursts in user's ears:
2070     // - always attenuate ring tones and notifications volume by 6dB
2071     // - if music is playing, always limit the volume to current music volume,
2072     // with a minimum threshold at -36dB so that notification is always perceived.
2073     if ((device &
2074         (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
2075         AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
2076         AudioSystem::DEVICE_OUT_WIRED_HEADSET |
2077         AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) &&
2078         ((getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) ||
2079          (stream == AudioSystem::SYSTEM)) &&
2080         streamDesc.mCanBeMuted) {
2081         volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
2082         // when the phone is ringing we must consider that music could have been paused just before
2083         // by the music application and behave as if music was active if the last music track was
2084         // just stopped
2085         if (outputDesc->mRefCount[AudioSystem::MUSIC] || mLimitRingtoneVolume) {
2086             float musicVol = computeVolume(AudioSystem::MUSIC, mStreams[AudioSystem::MUSIC].mIndexCur, output, device);
2087             float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
2088             if (volume > minVol) {
2089                 volume = minVol;
2090                 LOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
2091             }
2092         }
2093     }
2094 
2095     return volume;
2096 }
2097 
checkAndSetVolume(int stream,int index,audio_io_handle_t output,uint32_t device,int delayMs,bool force)2098 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs, bool force)
2099 {
2100 
2101     // do not change actual stream volume if the stream is muted
2102     if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
2103         LOGV("checkAndSetVolume() stream %d muted count %d", stream, mOutputs.valueFor(output)->mMuteCount[stream]);
2104         return NO_ERROR;
2105     }
2106 
2107     // do not change in call volume if bluetooth is connected and vice versa
2108     if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2109         (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
2110         LOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
2111              stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
2112         return INVALID_OPERATION;
2113     }
2114 
2115     float volume = computeVolume(stream, index, output, device);
2116     // We actually change the volume if:
2117     // - the float value returned by computeVolume() changed
2118     // - the force flag is set
2119     if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
2120             force) {
2121         mOutputs.valueFor(output)->mCurVolume[stream] = volume;
2122         LOGV("setStreamVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
2123         if (stream == AudioSystem::VOICE_CALL ||
2124             stream == AudioSystem::DTMF ||
2125             stream == AudioSystem::BLUETOOTH_SCO) {
2126             // offset value to reflect actual hardware volume that never reaches 0
2127             // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
2128             volume = 0.01 + 0.99 * volume;
2129             // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
2130             // enabled
2131             if (stream == AudioSystem::BLUETOOTH_SCO) {
2132                 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
2133             }
2134         }
2135 
2136         mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
2137     }
2138 
2139     if (stream == AudioSystem::VOICE_CALL ||
2140         stream == AudioSystem::BLUETOOTH_SCO) {
2141         float voiceVolume;
2142         // Force voice volume to max for bluetooth SCO as volume is managed by the headset
2143         if (stream == AudioSystem::VOICE_CALL) {
2144             voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2145         } else {
2146             voiceVolume = 1.0;
2147         }
2148 
2149         if (voiceVolume != mLastVoiceVolume && output == mHardwareOutput) {
2150             mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2151             mLastVoiceVolume = voiceVolume;
2152         }
2153     }
2154 
2155     return NO_ERROR;
2156 }
2157 
applyStreamVolumes(audio_io_handle_t output,uint32_t device,int delayMs,bool force)2158 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs, bool force)
2159 {
2160     LOGV("applyStreamVolumes() for output %d and device %x", output, device);
2161 
2162     for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2163         checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, device, delayMs, force);
2164     }
2165 }
2166 
setStrategyMute(routing_strategy strategy,bool on,audio_io_handle_t output,int delayMs)2167 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs)
2168 {
2169     LOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
2170     for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2171         if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
2172             setStreamMute(stream, on, output, delayMs);
2173         }
2174     }
2175 }
2176 
setStreamMute(int stream,bool on,audio_io_handle_t output,int delayMs)2177 void AudioPolicyManagerBase::setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs)
2178 {
2179     StreamDescriptor &streamDesc = mStreams[stream];
2180     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2181 
2182     LOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, outputDesc->mMuteCount[stream]);
2183 
2184     if (on) {
2185         if (outputDesc->mMuteCount[stream] == 0) {
2186             if (streamDesc.mCanBeMuted) {
2187                 checkAndSetVolume(stream, 0, output, outputDesc->device(), delayMs);
2188             }
2189         }
2190         // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2191         outputDesc->mMuteCount[stream]++;
2192     } else {
2193         if (outputDesc->mMuteCount[stream] == 0) {
2194             LOGW("setStreamMute() unmuting non muted stream!");
2195             return;
2196         }
2197         if (--outputDesc->mMuteCount[stream] == 0) {
2198             checkAndSetVolume(stream, streamDesc.mIndexCur, output, outputDesc->device(), delayMs);
2199         }
2200     }
2201 }
2202 
handleIncallSonification(int stream,bool starting,bool stateChange)2203 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2204 {
2205     // if the stream pertains to sonification strategy and we are in call we must
2206     // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2207     // in the device used for phone strategy and play the tone if the selected device does not
2208     // interfere with the device used for phone strategy
2209     // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2210     // many times as there are active tracks on the output
2211 
2212     if (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) {
2213         AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mHardwareOutput);
2214         LOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2215                 stream, starting, outputDesc->mDevice, stateChange);
2216         if (outputDesc->mRefCount[stream]) {
2217             int muteCount = 1;
2218             if (stateChange) {
2219                 muteCount = outputDesc->mRefCount[stream];
2220             }
2221             if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2222                 LOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2223                 for (int i = 0; i < muteCount; i++) {
2224                     setStreamMute(stream, starting, mHardwareOutput);
2225                 }
2226             } else {
2227                 LOGV("handleIncallSonification() high visibility");
2228                 if (outputDesc->device() & getDeviceForStrategy(STRATEGY_PHONE)) {
2229                     LOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2230                     for (int i = 0; i < muteCount; i++) {
2231                         setStreamMute(stream, starting, mHardwareOutput);
2232                     }
2233                 }
2234                 if (starting) {
2235                     mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2236                 } else {
2237                     mpClientInterface->stopTone();
2238                 }
2239             }
2240         }
2241     }
2242 }
2243 
isInCall()2244 bool AudioPolicyManagerBase::isInCall()
2245 {
2246     return isStateInCall(mPhoneState);
2247 }
2248 
isStateInCall(int state)2249 bool AudioPolicyManagerBase::isStateInCall(int state) {
2250     return ((state == AudioSystem::MODE_IN_CALL) ||
2251             (state == AudioSystem::MODE_IN_COMMUNICATION));
2252 }
2253 
needsDirectOuput(AudioSystem::stream_type stream,uint32_t samplingRate,uint32_t format,uint32_t channels,AudioSystem::output_flags flags,uint32_t device)2254 bool AudioPolicyManagerBase::needsDirectOuput(AudioSystem::stream_type stream,
2255                                     uint32_t samplingRate,
2256                                     uint32_t format,
2257                                     uint32_t channels,
2258                                     AudioSystem::output_flags flags,
2259                                     uint32_t device)
2260 {
2261    return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2262           (format !=0 && !AudioSystem::isLinearPCM(format)));
2263 }
2264 
getMaxEffectsCpuLoad()2265 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2266 {
2267     return MAX_EFFECTS_CPU_LOAD;
2268 }
2269 
getMaxEffectsMemory()2270 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2271 {
2272     return MAX_EFFECTS_MEMORY;
2273 }
2274 
2275 // --- AudioOutputDescriptor class implementation
2276 
AudioOutputDescriptor()2277 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor()
2278     : mId(0), mSamplingRate(0), mFormat(0), mChannels(0), mLatency(0),
2279     mFlags((AudioSystem::output_flags)0), mDevice(0), mOutput1(0), mOutput2(0)
2280 {
2281     // clear usage count for all stream types
2282     for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2283         mRefCount[i] = 0;
2284         mCurVolume[i] = -1.0;
2285         mMuteCount[i] = 0;
2286         mStopTime[i] = 0;
2287     }
2288 }
2289 
device()2290 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
2291 {
2292     uint32_t device = 0;
2293     if (isDuplicated()) {
2294         device = mOutput1->mDevice | mOutput2->mDevice;
2295     } else {
2296         device = mDevice;
2297     }
2298     return device;
2299 }
2300 
changeRefCount(AudioSystem::stream_type stream,int delta)2301 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
2302 {
2303     // forward usage count change to attached outputs
2304     if (isDuplicated()) {
2305         mOutput1->changeRefCount(stream, delta);
2306         mOutput2->changeRefCount(stream, delta);
2307     }
2308     if ((delta + (int)mRefCount[stream]) < 0) {
2309         LOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
2310         mRefCount[stream] = 0;
2311         return;
2312     }
2313     mRefCount[stream] += delta;
2314     LOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
2315 }
2316 
refCount()2317 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
2318 {
2319     uint32_t refcount = 0;
2320     for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2321         refcount += mRefCount[i];
2322     }
2323     return refcount;
2324 }
2325 
strategyRefCount(routing_strategy strategy)2326 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
2327 {
2328     uint32_t refCount = 0;
2329     for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2330         if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2331             refCount += mRefCount[i];
2332         }
2333     }
2334     return refCount;
2335 }
2336 
dump(int fd)2337 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
2338 {
2339     const size_t SIZE = 256;
2340     char buffer[SIZE];
2341     String8 result;
2342 
2343     snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2344     result.append(buffer);
2345     snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2346     result.append(buffer);
2347     snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2348     result.append(buffer);
2349     snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
2350     result.append(buffer);
2351     snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
2352     result.append(buffer);
2353     snprintf(buffer, SIZE, " Devices %08x\n", device());
2354     result.append(buffer);
2355     snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
2356     result.append(buffer);
2357     for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2358         snprintf(buffer, SIZE, " %02d     %.03f     %02d       %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
2359         result.append(buffer);
2360     }
2361     write(fd, result.string(), result.size());
2362 
2363     return NO_ERROR;
2364 }
2365 
2366 // --- AudioInputDescriptor class implementation
2367 
AudioInputDescriptor()2368 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor()
2369     : mSamplingRate(0), mFormat(0), mChannels(0),
2370       mAcoustics((AudioSystem::audio_in_acoustics)0), mDevice(0), mRefCount(0),
2371       mInputSource(0)
2372 {
2373 }
2374 
dump(int fd)2375 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
2376 {
2377     const size_t SIZE = 256;
2378     char buffer[SIZE];
2379     String8 result;
2380 
2381     snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2382     result.append(buffer);
2383     snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2384     result.append(buffer);
2385     snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2386     result.append(buffer);
2387     snprintf(buffer, SIZE, " Acoustics %08x\n", mAcoustics);
2388     result.append(buffer);
2389     snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
2390     result.append(buffer);
2391     snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
2392     result.append(buffer);
2393     write(fd, result.string(), result.size());
2394 
2395     return NO_ERROR;
2396 }
2397 
2398 // --- StreamDescriptor class implementation
2399 
dump(char * buffer,size_t size)2400 void AudioPolicyManagerBase::StreamDescriptor::dump(char* buffer, size_t size)
2401 {
2402     snprintf(buffer, size, "      %02d         %02d         %02d         %d\n",
2403             mIndexMin,
2404             mIndexMax,
2405             mIndexCur,
2406             mCanBeMuted);
2407 }
2408 
2409 // --- EffectDescriptor class implementation
2410 
dump(int fd)2411 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
2412 {
2413     const size_t SIZE = 256;
2414     char buffer[SIZE];
2415     String8 result;
2416 
2417     snprintf(buffer, SIZE, " I/O: %d\n", mIo);
2418     result.append(buffer);
2419     snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
2420     result.append(buffer);
2421     snprintf(buffer, SIZE, " Session: %d\n", mSession);
2422     result.append(buffer);
2423     snprintf(buffer, SIZE, " Name: %s\n",  mDesc.name);
2424     result.append(buffer);
2425     snprintf(buffer, SIZE, " %s\n",  mEnabled ? "Enabled" : "Disabled");
2426     result.append(buffer);
2427     write(fd, result.string(), result.size());
2428 
2429     return NO_ERROR;
2430 }
2431 
2432 
2433 
2434 }; // namespace android
2435