OSDN Git Service

audio policy: use configuration file
[android-x86/hardware-libhardware_legacy.git] / audio / AudioPolicyManagerBase.cpp
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 <hardware/audio.h>
23 #include <math.h>
24 #include <hardware_legacy/audio_policy_conf.h>
25
26 namespace android_audio_legacy {
27
28 // ----------------------------------------------------------------------------
29 // AudioPolicyInterface implementation
30 // ----------------------------------------------------------------------------
31
32
33 status_t AudioPolicyManagerBase::setDeviceConnectionState(AudioSystem::audio_devices device,
34                                                   AudioSystem::device_connection_state state,
35                                                   const char *device_address)
36 {
37     audio_io_handle_t output = 0;
38
39     ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
40
41     // connect/disconnect only 1 device at a time
42     if (AudioSystem::popCount(device) != 1) return BAD_VALUE;
43
44     if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
45         ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
46         return BAD_VALUE;
47     }
48
49     // handle output devices
50     if (AudioSystem::isOutputDevice(device)) {
51
52         if (!mHasA2dp && AudioSystem::isA2dpDevice(device)) {
53             ALOGE("setDeviceConnectionState() invalid device: %x", device);
54             return BAD_VALUE;
55         }
56
57         switch (state)
58         {
59         // handle output device connection
60         case AudioSystem::DEVICE_STATE_AVAILABLE:
61             if (mAvailableOutputDevices & device) {
62                 ALOGW("setDeviceConnectionState() device already connected: %x", device);
63                 return INVALID_OPERATION;
64             }
65             ALOGV("setDeviceConnectionState() connecting device %x", device);
66
67             // register new device as available
68             mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
69
70             output = checkOutputForDevice((audio_devices_t)device, state);
71             if (output == 0) {
72                 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
73                 return INVALID_OPERATION;
74             }
75             // handle A2DP device connection
76             if (mHasA2dp && AudioSystem::isA2dpDevice(device)) {
77                 AudioParameter param;
78                 param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
79                 mpClientInterface->setParameters(output, param.toString());
80                 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
81                 mA2dpSuspended = false;
82             } else if (AudioSystem::isBluetoothScoDevice(device)) {
83                 ALOGV("setDeviceConnectionState() BT SCO  device, address %s", device_address);
84                 // keep track of SCO device address
85                 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
86             }
87             break;
88         // handle output device disconnection
89         case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
90             if (!(mAvailableOutputDevices & device)) {
91                 ALOGW("setDeviceConnectionState() device not connected: %x", device);
92                 return INVALID_OPERATION;
93             }
94
95
96             ALOGV("setDeviceConnectionState() disconnecting device %x", device);
97             // remove device from available output devices
98             mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
99
100             output = checkOutputForDevice((audio_devices_t)device, state);
101             // handle A2DP device disconnection
102             if (mHasA2dp && AudioSystem::isA2dpDevice(device)) {
103                 mA2dpDeviceAddress = "";
104                 mA2dpSuspended = false;
105             } else if (AudioSystem::isBluetoothScoDevice(device)) {
106                 mScoDeviceAddress = "";
107             }
108             } break;
109
110         default:
111             ALOGE("setDeviceConnectionState() invalid state: %x", state);
112             return BAD_VALUE;
113         }
114
115         checkA2dpSuspend();
116         checkOutputForAllStrategies();
117         // outputs must be closed after checkOutputForAllStrategies() is executed
118         if (state == AudioSystem::DEVICE_STATE_UNAVAILABLE && output != 0) {
119             closeOutput(output);
120         }
121
122         updateDeviceForStrategy();
123         for (size_t i = 0; i < mOutputs.size(); i++) {
124             setOutputDevice(mOutputs.keyAt(i), getNewDevice(mOutputs.keyAt(i), true /*fromCache*/));
125         }
126
127         if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET) {
128             device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
129         } else if (device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO ||
130                    device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
131                    device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
132             device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
133         } else {
134             return NO_ERROR;
135         }
136     }
137     // handle input devices
138     if (AudioSystem::isInputDevice(device)) {
139
140         switch (state)
141         {
142         // handle input device connection
143         case AudioSystem::DEVICE_STATE_AVAILABLE: {
144             if (mAvailableInputDevices & device) {
145                 ALOGW("setDeviceConnectionState() device already connected: %d", device);
146                 return INVALID_OPERATION;
147             }
148             mAvailableInputDevices = (audio_devices_t)(mAvailableInputDevices | device);
149             }
150             break;
151
152         // handle input device disconnection
153         case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
154             if (!(mAvailableInputDevices & device)) {
155                 ALOGW("setDeviceConnectionState() device not connected: %d", device);
156                 return INVALID_OPERATION;
157             }
158             mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
159             } break;
160
161         default:
162             ALOGE("setDeviceConnectionState() invalid state: %x", state);
163             return BAD_VALUE;
164         }
165
166         audio_io_handle_t activeInput = getActiveInput();
167         if (activeInput != 0) {
168             AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
169             audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
170             if ((newDevice != 0) && (newDevice != inputDesc->mDevice)) {
171                 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
172                         inputDesc->mDevice, newDevice, activeInput);
173                 inputDesc->mDevice = newDevice;
174                 AudioParameter param = AudioParameter();
175                 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
176                 mpClientInterface->setParameters(activeInput, param.toString());
177             }
178         }
179
180         return NO_ERROR;
181     }
182
183     ALOGW("setDeviceConnectionState() invalid device: %x", device);
184     return BAD_VALUE;
185 }
186
187 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(AudioSystem::audio_devices device,
188                                                   const char *device_address)
189 {
190     AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
191     String8 address = String8(device_address);
192     if (AudioSystem::isOutputDevice(device)) {
193         if (device & mAvailableOutputDevices) {
194             if (AudioSystem::isA2dpDevice(device) &&
195                 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
196                 return state;
197             }
198             if (AudioSystem::isBluetoothScoDevice(device) &&
199                 address != "" && mScoDeviceAddress != address) {
200                 return state;
201             }
202             state = AudioSystem::DEVICE_STATE_AVAILABLE;
203         }
204     } else if (AudioSystem::isInputDevice(device)) {
205         if (device & mAvailableInputDevices) {
206             state = AudioSystem::DEVICE_STATE_AVAILABLE;
207         }
208     }
209
210     return state;
211 }
212
213 void AudioPolicyManagerBase::setPhoneState(int state)
214 {
215     ALOGV("setPhoneState() state %d", state);
216     audio_devices_t newDevice = (audio_devices_t)0;
217     if (state < 0 || state >= AudioSystem::NUM_MODES) {
218         ALOGW("setPhoneState() invalid state %d", state);
219         return;
220     }
221
222     if (state == mPhoneState ) {
223         ALOGW("setPhoneState() setting same state %d", state);
224         return;
225     }
226
227     // if leaving call state, handle special case of active streams
228     // pertaining to sonification strategy see handleIncallSonification()
229     if (isInCall()) {
230         ALOGV("setPhoneState() in call state management: new state is %d", state);
231         for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
232             handleIncallSonification(stream, false, true);
233         }
234     }
235
236     // store previous phone state for management of sonification strategy below
237     int oldState = mPhoneState;
238     mPhoneState = state;
239     bool force = false;
240
241     // are we entering or starting a call
242     if (!isStateInCall(oldState) && isStateInCall(state)) {
243         ALOGV("  Entering call in setPhoneState()");
244         // force routing command to audio hardware when starting a call
245         // even if no device change is needed
246         force = true;
247     } else if (isStateInCall(oldState) && !isStateInCall(state)) {
248         ALOGV("  Exiting call in setPhoneState()");
249         // force routing command to audio hardware when exiting a call
250         // even if no device change is needed
251         force = true;
252     } else if (isStateInCall(state) && (state != oldState)) {
253         ALOGV("  Switching between telephony and VoIP in setPhoneState()");
254         // force routing command to audio hardware when switching between telephony and VoIP
255         // even if no device change is needed
256         force = true;
257     }
258
259     // check for device and output changes triggered by new phone state
260     newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
261     checkA2dpSuspend();
262     checkOutputForAllStrategies();
263     updateDeviceForStrategy();
264
265     AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
266
267     // force routing command to audio hardware when ending call
268     // even if no device change is needed
269     if (isStateInCall(oldState) && newDevice == 0) {
270         newDevice = hwOutputDesc->device();
271     }
272
273     // when changing from ring tone to in call mode, mute the ringing tone
274     // immediately and delay the route change to avoid sending the ring tone
275     // tail into the earpiece or headset.
276     int delayMs = 0;
277     if (isStateInCall(state) && oldState == AudioSystem::MODE_RINGTONE) {
278         // delay the device change command by twice the output latency to have some margin
279         // and be sure that audio buffers not yet affected by the mute are out when
280         // we actually apply the route change
281         delayMs = hwOutputDesc->mLatency*2;
282         setStreamMute(AudioSystem::RING, true, mPrimaryOutput);
283     }
284
285     // change routing is necessary
286     setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
287
288     // if entering in call state, handle special case of active streams
289     // pertaining to sonification strategy see handleIncallSonification()
290     if (isStateInCall(state)) {
291         ALOGV("setPhoneState() in call state management: new state is %d", state);
292         // unmute the ringing tone after a sufficient delay if it was muted before
293         // setting output device above
294         if (oldState == AudioSystem::MODE_RINGTONE) {
295             setStreamMute(AudioSystem::RING, false, mPrimaryOutput, MUTE_TIME_MS);
296         }
297         for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
298             handleIncallSonification(stream, true, true);
299         }
300     }
301
302     // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
303     if (state == AudioSystem::MODE_RINGTONE &&
304         isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
305         mLimitRingtoneVolume = true;
306     } else {
307         mLimitRingtoneVolume = false;
308     }
309 }
310
311 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
312 {
313     ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
314
315     bool forceVolumeReeval = false;
316     switch(usage) {
317     case AudioSystem::FOR_COMMUNICATION:
318         if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
319             config != AudioSystem::FORCE_NONE) {
320             ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
321             return;
322         }
323         forceVolumeReeval = true;
324         mForceUse[usage] = config;
325         break;
326     case AudioSystem::FOR_MEDIA:
327         if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
328             config != AudioSystem::FORCE_WIRED_ACCESSORY &&
329             config != AudioSystem::FORCE_ANALOG_DOCK &&
330             config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE) {
331             ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
332             return;
333         }
334         mForceUse[usage] = config;
335         break;
336     case AudioSystem::FOR_RECORD:
337         if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
338             config != AudioSystem::FORCE_NONE) {
339             ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
340             return;
341         }
342         mForceUse[usage] = config;
343         break;
344     case AudioSystem::FOR_DOCK:
345         if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
346             config != AudioSystem::FORCE_BT_DESK_DOCK &&
347             config != AudioSystem::FORCE_WIRED_ACCESSORY &&
348             config != AudioSystem::FORCE_ANALOG_DOCK &&
349             config != AudioSystem::FORCE_DIGITAL_DOCK) {
350             ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
351         }
352         forceVolumeReeval = true;
353         mForceUse[usage] = config;
354         break;
355     default:
356         ALOGW("setForceUse() invalid usage %d", usage);
357         break;
358     }
359
360     // check for device and output changes triggered by new force usage
361     checkA2dpSuspend();
362     checkOutputForAllStrategies();
363     updateDeviceForStrategy();
364     for (size_t i = 0; i < mOutputs.size(); i++) {
365         audio_io_handle_t output = mOutputs.keyAt(i);
366         audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
367         setOutputDevice(output, newDevice, true);
368         if (forceVolumeReeval) {
369             applyStreamVolumes(output, newDevice, 0, true);
370         }
371     }
372
373     audio_io_handle_t activeInput = getActiveInput();
374     if (activeInput != 0) {
375         AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
376         audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
377         if ((newDevice != 0) && (newDevice != inputDesc->mDevice)) {
378             ALOGV("setForceUse() changing device from %x to %x for input %d",
379                     inputDesc->mDevice, newDevice, activeInput);
380             inputDesc->mDevice = newDevice;
381             AudioParameter param = AudioParameter();
382             param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
383             mpClientInterface->setParameters(activeInput, param.toString());
384         }
385     }
386
387 }
388
389 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
390 {
391     return mForceUse[usage];
392 }
393
394 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
395 {
396     ALOGV("setSystemProperty() property %s, value %s", property, value);
397     if (strcmp(property, "ro.camera.sound.forced") == 0) {
398         if (atoi(value)) {
399             ALOGV("ENFORCED_AUDIBLE cannot be muted");
400             mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false;
401         } else {
402             ALOGV("ENFORCED_AUDIBLE can be muted");
403             mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true;
404         }
405     }
406 }
407
408 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
409                                     uint32_t samplingRate,
410                                     uint32_t format,
411                                     uint32_t channels,
412                                     AudioSystem::output_flags flags)
413 {
414     audio_io_handle_t output = 0;
415     uint32_t latency = 0;
416     routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
417     audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
418     ALOGV("getOutput() stream %d, samplingRate %d, format %d, channels %x, flags %x", stream, samplingRate, format, channels, flags);
419
420 #ifdef AUDIO_POLICY_TEST
421     if (mCurOutput != 0) {
422         ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channels %x, mDirectOutput %d",
423                 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
424
425         if (mTestOutputs[mCurOutput] == 0) {
426             ALOGV("getOutput() opening test output");
427             AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
428             outputDesc->mDevice = mTestDevice;
429             outputDesc->mSamplingRate = mTestSamplingRate;
430             outputDesc->mFormat = mTestFormat;
431             outputDesc->mChannels = mTestChannels;
432             outputDesc->mLatency = mTestLatencyMs;
433             outputDesc->mFlags = (AudioSystem::output_flags)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
434             outputDesc->mRefCount[stream] = 0;
435             mTestOutputs[mCurOutput] = mpClientInterface->openOutput(&outputDesc->mDevice,
436                                             &outputDesc->mSamplingRate,
437                                             &outputDesc->mFormat,
438                                             &outputDesc->mChannels,
439                                             &outputDesc->mLatency,
440                                             outputDesc->mFlags);
441             if (mTestOutputs[mCurOutput]) {
442                 AudioParameter outputCmd = AudioParameter();
443                 outputCmd.addInt(String8("set_id"),mCurOutput);
444                 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
445                 addOutput(mTestOutputs[mCurOutput], outputDesc);
446             }
447         }
448         return mTestOutputs[mCurOutput];
449     }
450 #endif //AUDIO_POLICY_TEST
451
452     // open a direct output if required by specified parameters
453     if (needsDirectOuput(stream, samplingRate, format, channels, flags, device)) {
454
455         ALOGV("getOutput() opening direct output device %x", device);
456         AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
457         outputDesc->mDevice = device;
458         outputDesc->mSamplingRate = samplingRate;
459         outputDesc->mFormat = format;
460         outputDesc->mChannels = channels;
461         outputDesc->mLatency = 0;
462         outputDesc->mFlags = (AudioSystem::output_flags)(flags | AudioSystem::OUTPUT_FLAG_DIRECT);
463         outputDesc->mRefCount[stream] = 0;
464         outputDesc->mStopTime[stream] = 0;
465         output = mpClientInterface->openOutput((uint32_t *)&outputDesc->mDevice,
466                                         &outputDesc->mSamplingRate,
467                                         &outputDesc->mFormat,
468                                         &outputDesc->mChannels,
469                                         &outputDesc->mLatency,
470                                         outputDesc->mFlags);
471
472         // only accept an output with the requeted parameters
473         if (output == 0 ||
474             (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
475             (format != 0 && format != outputDesc->mFormat) ||
476             (channels != 0 && channels != outputDesc->mChannels)) {
477             ALOGV("getOutput() failed opening direct output: samplingRate %d, format %d, channels %d",
478                     samplingRate, format, channels);
479             if (output != 0) {
480                 mpClientInterface->closeOutput(output);
481             }
482             delete outputDesc;
483             return 0;
484         }
485         addOutput(output, outputDesc);
486         return output;
487     }
488
489     if (channels != 0 && channels != AudioSystem::CHANNEL_OUT_MONO &&
490         channels != AudioSystem::CHANNEL_OUT_STEREO) {
491         return 0;
492     }
493     // open a non direct output
494
495     // get which output is suitable for the specified stream. The actual routing change will happen
496     // when startOutput() will be called
497     SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device);
498
499     output = selectOutput(outputs, flags);
500
501     ALOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d, format %d, channels %x, flags %x",
502                 stream, samplingRate, format, channels, flags);
503
504     ALOGV("getOutput() returns output %d", output);
505
506     return output;
507 }
508
509 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
510                                                        AudioSystem::output_flags flags)
511 {
512     // select one output among several that provide a path to a particular device or set of
513     // devices (the list was previously build by getOutputsForDevice()).
514     // The priority is as follows:
515     // 1: the output with the highest number of requested policy flags
516     // 2: the primary output
517     // 3: the first output in the list
518
519     if (outputs.size() == 0) {
520         return 0;
521     }
522     if (outputs.size() == 1) {
523         return outputs[0];
524     }
525
526     int maxCommonFlags = 0;
527     audio_io_handle_t outputFlags = 0;
528     audio_io_handle_t outputPrimary = 0;
529
530     for (size_t i = 0; i < outputs.size(); i++) {
531         AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
532         if (!outputDesc->isDuplicated()) {
533             int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
534             if (commonFlags > maxCommonFlags) {
535                 outputFlags = outputs[i];
536                 maxCommonFlags = commonFlags;
537                 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
538             }
539             if (outputDesc->mProfile->mFlags & AUDIO_POLICY_OUTPUT_FLAG_PRIMARY) {
540                 outputPrimary = outputs[i];
541             }
542         }
543     }
544
545     if (outputFlags != 0) {
546         return outputFlags;
547     }
548     if (outputPrimary != 0) {
549         return outputPrimary;
550     }
551
552     return outputs[0];
553 }
554
555 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
556                                              AudioSystem::stream_type stream,
557                                              int session)
558 {
559     ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
560     ssize_t index = mOutputs.indexOfKey(output);
561     if (index < 0) {
562         ALOGW("startOutput() unknow output %d", output);
563         return BAD_VALUE;
564     }
565
566     AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
567
568     // increment usage count for this stream on the requested output:
569     // NOTE that the usage count is the same for duplicated output and hardware output which is
570     // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
571     outputDesc->changeRefCount(stream, 1);
572
573     if (outputDesc->mRefCount[stream] == 1) {
574         audio_devices_t prevDevice = outputDesc->device();
575         audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
576
577         // force a device change if any other output is active, is managed by the same and hw
578         // module and has a current device selection that differs from newly selected device.
579         // In this case, the audio HAL must receive the new device selection so that it can
580         // change the device currently selected by the other active output.
581         bool force = false;
582         for (size_t i = 0; i < mOutputs.size(); i++) {
583             AudioOutputDescriptor *desc = mOutputs.valueAt(i);
584             if (output != mOutputs.keyAt(i) &&
585                     desc->refCount() != 0 &&
586                     outputDesc->sharesHwModuleWith(desc) &&
587                     desc->device() != newDevice) {
588                 force = true;
589                 break;
590             }
591         }
592         setOutputDevice(output, newDevice, force);
593
594         // handle special case for sonification while in call
595         if (isInCall()) {
596             handleIncallSonification(stream, true, false);
597         }
598
599         // apply volume rules for current stream and device if necessary
600         checkAndSetVolume(stream,
601                           mStreams[stream].getVolumeIndex((audio_devices_t)newDevice),
602                           output,
603                           newDevice);
604
605         // update the outputs if starting an output with a stream that can affect notification
606         // routing
607         handleNotificationRoutingForStream(stream);
608     }
609     return NO_ERROR;
610 }
611
612
613 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
614                                             AudioSystem::stream_type stream,
615                                             int session)
616 {
617     ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
618     ssize_t index = mOutputs.indexOfKey(output);
619     if (index < 0) {
620         ALOGW("stopOutput() unknow output %d", output);
621         return BAD_VALUE;
622     }
623
624     AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
625
626     // handle special case for sonification while in call
627     if (isInCall()) {
628         handleIncallSonification(stream, false, false);
629     }
630
631     if (outputDesc->mRefCount[stream] > 0) {
632         // decrement usage count of this stream on the output
633         outputDesc->changeRefCount(stream, -1);
634         // store time at which the stream was stopped - see isStreamActive()
635         if (outputDesc->mRefCount[stream] == 0) {
636             outputDesc->mStopTime[stream] = systemTime();
637             audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
638             // delay the device switch by twice the latency because stopOutput() is executed when
639             // the track stop() command is received and at that time the audio track buffer can
640             // still contain data that needs to be drained. The latency only covers the audio HAL
641             // and kernel buffers. Also the latency does not always include additional delay in the
642             // audio path (audio DSP, CODEC ...)
643             setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
644
645             // force restoring the device selection on other active outputs if it differs from the
646             // one being selected for this output
647             for (size_t i = 0; i < mOutputs.size(); i++) {
648                 audio_io_handle_t curOutput = mOutputs.keyAt(i);
649                 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
650                 if (curOutput != output &&
651                         desc->refCount() != 0 &&
652                         outputDesc->sharesHwModuleWith(desc) &&
653                         newDevice != desc->device()) {
654                     setOutputDevice(curOutput,
655                                     getNewDevice(curOutput, false /*fromCache*/),
656                                     true,
657                                     outputDesc->mLatency*2);
658                 }
659             }
660             // update the outputs if stopping one with a stream that can affect notification routing
661             handleNotificationRoutingForStream(stream);
662         }
663         return NO_ERROR;
664     } else {
665         ALOGW("stopOutput() refcount is already 0 for output %d", output);
666         return INVALID_OPERATION;
667     }
668 }
669
670 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
671 {
672     ALOGV("releaseOutput() %d", output);
673     ssize_t index = mOutputs.indexOfKey(output);
674     if (index < 0) {
675         ALOGW("releaseOutput() releasing unknown output %d", output);
676         return;
677     }
678
679 #ifdef AUDIO_POLICY_TEST
680     int testIndex = testOutputIndex(output);
681     if (testIndex != 0) {
682         AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
683         if (outputDesc->refCount() == 0) {
684             mpClientInterface->closeOutput(output);
685             delete mOutputs.valueAt(index);
686             mOutputs.removeItem(output);
687             mTestOutputs[testIndex] = 0;
688         }
689         return;
690     }
691 #endif //AUDIO_POLICY_TEST
692
693     if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
694         mpClientInterface->closeOutput(output);
695         delete mOutputs.valueAt(index);
696         mOutputs.removeItem(output);
697     }
698
699 }
700
701 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
702                                     uint32_t samplingRate,
703                                     uint32_t format,
704                                     uint32_t channels,
705                                     AudioSystem::audio_in_acoustics acoustics)
706 {
707     audio_io_handle_t input = 0;
708     audio_devices_t device = getDeviceForInputSource(inputSource);
709
710     ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channels %x, acoustics %x",
711           inputSource, samplingRate, format, channels, acoustics);
712
713     if (device == 0) {
714         ALOGW("getInput() could not find device for inputSource %d", inputSource);
715         return 0;
716     }
717
718     // adapt channel selection to input source
719     switch(inputSource) {
720     case AUDIO_SOURCE_VOICE_UPLINK:
721         channels = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
722         break;
723     case AUDIO_SOURCE_VOICE_DOWNLINK:
724         channels = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
725         break;
726     case AUDIO_SOURCE_VOICE_CALL:
727         channels = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
728         break;
729     default:
730         break;
731     }
732
733     IOProfile *profile = getInputProfile(device,
734                                          samplingRate,
735                                          format,
736                                          channels);
737     if (profile == NULL) {
738         ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d,"
739                 "channels %04x",
740                 device, samplingRate, format, channels);
741         return 0;
742     }
743
744     AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
745
746     inputDesc->mInputSource = inputSource;
747     inputDesc->mDevice = device;
748     inputDesc->mSamplingRate = samplingRate;
749     inputDesc->mFormat = format;
750     inputDesc->mChannels = channels;
751     inputDesc->mAcoustics = acoustics;
752     inputDesc->mRefCount = 0;
753     input = mpClientInterface->openInput((uint32_t *)&inputDesc->mDevice,
754                                     &inputDesc->mSamplingRate,
755                                     &inputDesc->mFormat,
756                                     &inputDesc->mChannels,
757                                     (audio_in_acoustics_t) inputDesc->mAcoustics);
758
759     // only accept input with the exact requested set of parameters
760     if (input == 0 ||
761         (samplingRate != inputDesc->mSamplingRate) ||
762         (format != inputDesc->mFormat) ||
763         (channels != inputDesc->mChannels)) {
764         ALOGV("getInput() failed opening input: samplingRate %d, format %d, channels %d",
765                 samplingRate, format, channels);
766         if (input != 0) {
767             mpClientInterface->closeInput(input);
768         }
769         delete inputDesc;
770         return 0;
771     }
772     mInputs.add(input, inputDesc);
773     return input;
774 }
775
776 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
777 {
778     ALOGV("startInput() input %d", input);
779     ssize_t index = mInputs.indexOfKey(input);
780     if (index < 0) {
781         ALOGW("startInput() unknow input %d", input);
782         return BAD_VALUE;
783     }
784     AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
785
786 #ifdef AUDIO_POLICY_TEST
787     if (mTestInput == 0)
788 #endif //AUDIO_POLICY_TEST
789     {
790         // refuse 2 active AudioRecord clients at the same time
791         if (getActiveInput() != 0) {
792             ALOGW("startInput() input %d failed: other input already started", input);
793             return INVALID_OPERATION;
794         }
795     }
796
797     AudioParameter param = AudioParameter();
798     param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
799
800     param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
801     ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
802
803     mpClientInterface->setParameters(input, param.toString());
804
805     inputDesc->mRefCount = 1;
806     return NO_ERROR;
807 }
808
809 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
810 {
811     ALOGV("stopInput() input %d", input);
812     ssize_t index = mInputs.indexOfKey(input);
813     if (index < 0) {
814         ALOGW("stopInput() unknow input %d", input);
815         return BAD_VALUE;
816     }
817     AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
818
819     if (inputDesc->mRefCount == 0) {
820         ALOGW("stopInput() input %d already stopped", input);
821         return INVALID_OPERATION;
822     } else {
823         AudioParameter param = AudioParameter();
824         param.addInt(String8(AudioParameter::keyRouting), 0);
825         mpClientInterface->setParameters(input, param.toString());
826         inputDesc->mRefCount = 0;
827         return NO_ERROR;
828     }
829 }
830
831 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
832 {
833     ALOGV("releaseInput() %d", input);
834     ssize_t index = mInputs.indexOfKey(input);
835     if (index < 0) {
836         ALOGW("releaseInput() releasing unknown input %d", input);
837         return;
838     }
839     mpClientInterface->closeInput(input);
840     delete mInputs.valueAt(index);
841     mInputs.removeItem(input);
842     ALOGV("releaseInput() exit");
843 }
844
845 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
846                                             int indexMin,
847                                             int indexMax)
848 {
849     ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
850     if (indexMin < 0 || indexMin >= indexMax) {
851         ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
852         return;
853     }
854     mStreams[stream].mIndexMin = indexMin;
855     mStreams[stream].mIndexMax = indexMax;
856 }
857
858 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
859                                                       int index,
860                                                       audio_devices_t device)
861 {
862
863     if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
864         return BAD_VALUE;
865     }
866     if (!audio_is_output_device(device)) {
867         return BAD_VALUE;
868     }
869
870     // Force max volume if stream cannot be muted
871     if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
872
873     ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
874           stream, device, index);
875
876     // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
877     // clear all device specific values
878     if (device == AUDIO_DEVICE_OUT_DEFAULT) {
879         mStreams[stream].mIndexCur.clear();
880     }
881     mStreams[stream].mIndexCur.add(device, index);
882
883     // compute and apply stream volume on all outputs according to connected device
884     status_t status = NO_ERROR;
885     for (size_t i = 0; i < mOutputs.size(); i++) {
886         audio_devices_t curDevice =
887                 getDeviceForVolume((audio_devices_t)mOutputs.valueAt(i)->device());
888         if (device == curDevice) {
889             status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
890             if (volStatus != NO_ERROR) {
891                 status = volStatus;
892             }
893         }
894     }
895     return status;
896 }
897
898 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
899                                                       int *index,
900                                                       audio_devices_t device)
901 {
902     if (index == NULL) {
903         return BAD_VALUE;
904     }
905     if (!audio_is_output_device(device)) {
906         return BAD_VALUE;
907     }
908     // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
909     // the strategy the stream belongs to.
910     if (device == AUDIO_DEVICE_OUT_DEFAULT) {
911         device = (audio_devices_t)getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
912     }
913     device = getDeviceForVolume(device);
914
915     *index =  mStreams[stream].getVolumeIndex(device);
916     ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
917     return NO_ERROR;
918 }
919
920 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(effect_descriptor_t *desc)
921 {
922     ALOGV("getOutputForEffect()");
923     // apply simple rule where global effects are attached to the same output as MUSIC streams
924     return getOutput(AudioSystem::MUSIC);
925 }
926
927 status_t AudioPolicyManagerBase::registerEffect(effect_descriptor_t *desc,
928                                 audio_io_handle_t io,
929                                 uint32_t strategy,
930                                 int session,
931                                 int id)
932 {
933     ssize_t index = mOutputs.indexOfKey(io);
934     if (index < 0) {
935         index = mInputs.indexOfKey(io);
936         if (index < 0) {
937             ALOGW("registerEffect() unknown io %d", io);
938             return INVALID_OPERATION;
939         }
940     }
941
942     if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
943         ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
944                 desc->name, desc->memoryUsage);
945         return INVALID_OPERATION;
946     }
947     mTotalEffectsMemory += desc->memoryUsage;
948     ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
949             desc->name, io, strategy, session, id);
950     ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
951
952     EffectDescriptor *pDesc = new EffectDescriptor();
953     memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
954     pDesc->mIo = io;
955     pDesc->mStrategy = (routing_strategy)strategy;
956     pDesc->mSession = session;
957     pDesc->mEnabled = false;
958
959     mEffects.add(id, pDesc);
960
961     return NO_ERROR;
962 }
963
964 status_t AudioPolicyManagerBase::unregisterEffect(int id)
965 {
966     ssize_t index = mEffects.indexOfKey(id);
967     if (index < 0) {
968         ALOGW("unregisterEffect() unknown effect ID %d", id);
969         return INVALID_OPERATION;
970     }
971
972     EffectDescriptor *pDesc = mEffects.valueAt(index);
973
974     setEffectEnabled(pDesc, false);
975
976     if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
977         ALOGW("unregisterEffect() memory %d too big for total %d",
978                 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
979         pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
980     }
981     mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
982     ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
983             pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
984
985     mEffects.removeItem(id);
986     delete pDesc;
987
988     return NO_ERROR;
989 }
990
991 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
992 {
993     ssize_t index = mEffects.indexOfKey(id);
994     if (index < 0) {
995         ALOGW("unregisterEffect() unknown effect ID %d", id);
996         return INVALID_OPERATION;
997     }
998
999     return setEffectEnabled(mEffects.valueAt(index), enabled);
1000 }
1001
1002 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1003 {
1004     if (enabled == pDesc->mEnabled) {
1005         ALOGV("setEffectEnabled(%s) effect already %s",
1006              enabled?"true":"false", enabled?"enabled":"disabled");
1007         return INVALID_OPERATION;
1008     }
1009
1010     if (enabled) {
1011         if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1012             ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1013                  pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1014             return INVALID_OPERATION;
1015         }
1016         mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1017         ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1018     } else {
1019         if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1020             ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1021                     pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1022             pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1023         }
1024         mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1025         ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1026     }
1027     pDesc->mEnabled = enabled;
1028     return NO_ERROR;
1029 }
1030
1031 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1032 {
1033     nsecs_t sysTime = systemTime();
1034     for (size_t i = 0; i < mOutputs.size(); i++) {
1035         if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
1036             ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
1037             return true;
1038         }
1039     }
1040     return false;
1041 }
1042
1043
1044 status_t AudioPolicyManagerBase::dump(int fd)
1045 {
1046     const size_t SIZE = 256;
1047     char buffer[SIZE];
1048     String8 result;
1049
1050     snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1051     result.append(buffer);
1052
1053     snprintf(buffer, SIZE, " Hardware Output: %d\n", mPrimaryOutput);
1054     result.append(buffer);
1055     snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1056     result.append(buffer);
1057     snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1058     result.append(buffer);
1059     snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1060     result.append(buffer);
1061     snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1062     result.append(buffer);
1063     snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1064     result.append(buffer);
1065     snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1066     result.append(buffer);
1067     snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1068     result.append(buffer);
1069     snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1070     result.append(buffer);
1071     snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1072     result.append(buffer);
1073     write(fd, result.string(), result.size());
1074
1075     snprintf(buffer, SIZE, "\nOutput Profiles dump:\n");
1076     write(fd, buffer, strlen(buffer));
1077     for (size_t i = 0; i < mOutputProfiles.size(); i++) {
1078         snprintf(buffer, SIZE, "- Output Profile %d:\n", i + 1);
1079         write(fd, buffer, strlen(buffer));
1080         mOutputProfiles[i]->dump(fd);
1081     }
1082
1083     snprintf(buffer, SIZE, "\nInput Profiles dump:\n");
1084     write(fd, buffer, strlen(buffer));
1085     for (size_t i = 0; i < mInputProfiles.size(); i++) {
1086         snprintf(buffer, SIZE, "- Input Profile %d:\n", i + 1);
1087         write(fd, buffer, strlen(buffer));
1088         mInputProfiles[i]->dump(fd);
1089     }
1090
1091     snprintf(buffer, SIZE, "\nOutputs dump:\n");
1092     write(fd, buffer, strlen(buffer));
1093     for (size_t i = 0; i < mOutputs.size(); i++) {
1094         snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1095         write(fd, buffer, strlen(buffer));
1096         mOutputs.valueAt(i)->dump(fd);
1097     }
1098
1099     snprintf(buffer, SIZE, "\nInputs dump:\n");
1100     write(fd, buffer, strlen(buffer));
1101     for (size_t i = 0; i < mInputs.size(); i++) {
1102         snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1103         write(fd, buffer, strlen(buffer));
1104         mInputs.valueAt(i)->dump(fd);
1105     }
1106
1107     snprintf(buffer, SIZE, "\nStreams dump:\n");
1108     write(fd, buffer, strlen(buffer));
1109     snprintf(buffer, SIZE,
1110              " Stream  Can be muted  Index Min  Index Max  Index Cur [device : index]...\n");
1111     write(fd, buffer, strlen(buffer));
1112     for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1113         snprintf(buffer, SIZE, " %02d      ", i);
1114         write(fd, buffer, strlen(buffer));
1115         mStreams[i].dump(fd);
1116     }
1117
1118     snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1119             (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1120     write(fd, buffer, strlen(buffer));
1121
1122     snprintf(buffer, SIZE, "Registered effects:\n");
1123     write(fd, buffer, strlen(buffer));
1124     for (size_t i = 0; i < mEffects.size(); i++) {
1125         snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1126         write(fd, buffer, strlen(buffer));
1127         mEffects.valueAt(i)->dump(fd);
1128     }
1129
1130
1131     return NO_ERROR;
1132 }
1133
1134 // ----------------------------------------------------------------------------
1135 // AudioPolicyManagerBase
1136 // ----------------------------------------------------------------------------
1137
1138 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1139     :
1140 #ifdef AUDIO_POLICY_TEST
1141     Thread(false),
1142 #endif //AUDIO_POLICY_TEST
1143     mAvailableOutputDevices((audio_devices_t)0),
1144     mPhoneState(AudioSystem::MODE_NORMAL),
1145     mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1146     mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1147     mA2dpSuspended(false), mHasA2dp(false)
1148 {
1149     mpClientInterface = clientInterface;
1150
1151     for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1152         mForceUse[i] = AudioSystem::FORCE_NONE;
1153     }
1154
1155     initializeVolumeCurves();
1156
1157     mA2dpDeviceAddress = String8("");
1158     mScoDeviceAddress = String8("");
1159
1160     if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1161         ALOGE("could not load audio policy configuration file");
1162     }
1163
1164     // open all output streams needed to access attached devices
1165     for (size_t i = 0; i < mOutputProfiles.size(); i++)
1166     {
1167         const IOProfile *outProfile = mOutputProfiles[i];
1168
1169         if (outProfile->mSupportedDevices & mAttachedOutputDevices) {
1170             AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1171
1172             outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1173                                                         outProfile->mSupportedDevices);
1174             outputDesc->mSamplingRate = outProfile->mSamplingRates[0];
1175             outputDesc->mFormat = outProfile->mFormats[0];
1176             outputDesc->mChannels = outProfile->mChannelMasks[0];
1177             outputDesc->mFlags = (AudioSystem::output_flags)outProfile->mFlags;
1178             audio_io_handle_t output = mpClientInterface->openOutput(
1179                                             (uint32_t *)&outputDesc->mDevice,
1180                                             &outputDesc->mSamplingRate,
1181                                             &outputDesc->mFormat,
1182                                             &outputDesc->mChannels,
1183                                             &outputDesc->mLatency,
1184                                             outputDesc->mFlags);
1185             if (output == 0) {
1186                 delete outputDesc;
1187             } else {
1188                 mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1189                                         (outProfile->mSupportedDevices & mAttachedOutputDevices));
1190                 if (outProfile->mFlags & AUDIO_POLICY_OUTPUT_FLAG_PRIMARY) {
1191                     mPrimaryOutput = output;
1192                 }
1193                 addOutput(output, outputDesc);
1194                 setOutputDevice(output,
1195                                 (audio_devices_t)(mDefaultOutputDevice &
1196                                                     outProfile->mSupportedDevices),
1197                                 true);
1198             }
1199         }
1200     }
1201
1202     ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1203              "Not output found for attached devices %08x",
1204              (mAttachedOutputDevices & ~mAvailableOutputDevices));
1205
1206     ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1207
1208     updateDeviceForStrategy();
1209 #ifdef AUDIO_POLICY_TEST
1210     if (mPrimaryOutput != 0) {
1211         AudioParameter outputCmd = AudioParameter();
1212         outputCmd.addInt(String8("set_id"), 0);
1213         mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1214
1215         mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
1216         mTestSamplingRate = 44100;
1217         mTestFormat = AudioSystem::PCM_16_BIT;
1218         mTestChannels =  AudioSystem::CHANNEL_OUT_STEREO;
1219         mTestLatencyMs = 0;
1220         mCurOutput = 0;
1221         mDirectOutput = false;
1222         for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1223             mTestOutputs[i] = 0;
1224         }
1225
1226         const size_t SIZE = 256;
1227         char buffer[SIZE];
1228         snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1229         run(buffer, ANDROID_PRIORITY_AUDIO);
1230     }
1231 #endif //AUDIO_POLICY_TEST
1232 }
1233
1234 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1235 {
1236 #ifdef AUDIO_POLICY_TEST
1237     exit();
1238 #endif //AUDIO_POLICY_TEST
1239    for (size_t i = 0; i < mOutputs.size(); i++) {
1240         mpClientInterface->closeOutput(mOutputs.keyAt(i));
1241         delete mOutputs.valueAt(i);
1242    }
1243    mOutputs.clear();
1244    for (size_t i = 0; i < mInputs.size(); i++) {
1245         mpClientInterface->closeInput(mInputs.keyAt(i));
1246         delete mInputs.valueAt(i);
1247    }
1248    mInputs.clear();
1249    for (size_t i = 0; i < mOutputProfiles.size(); i++) {
1250         delete mOutputProfiles[i];
1251    }
1252    for (size_t i = 0; i < mInputProfiles.size(); i++) {
1253         delete mInputProfiles[i];
1254    }
1255 }
1256
1257 status_t AudioPolicyManagerBase::initCheck()
1258 {
1259     return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1260 }
1261
1262 #ifdef AUDIO_POLICY_TEST
1263 bool AudioPolicyManagerBase::threadLoop()
1264 {
1265     ALOGV("entering threadLoop()");
1266     while (!exitPending())
1267     {
1268         String8 command;
1269         int valueInt;
1270         String8 value;
1271
1272         Mutex::Autolock _l(mLock);
1273         mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1274
1275         command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1276         AudioParameter param = AudioParameter(command);
1277
1278         if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1279             valueInt != 0) {
1280             ALOGV("Test command %s received", command.string());
1281             String8 target;
1282             if (param.get(String8("target"), target) != NO_ERROR) {
1283                 target = "Manager";
1284             }
1285             if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1286                 param.remove(String8("test_cmd_policy_output"));
1287                 mCurOutput = valueInt;
1288             }
1289             if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1290                 param.remove(String8("test_cmd_policy_direct"));
1291                 if (value == "false") {
1292                     mDirectOutput = false;
1293                 } else if (value == "true") {
1294                     mDirectOutput = true;
1295                 }
1296             }
1297             if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1298                 param.remove(String8("test_cmd_policy_input"));
1299                 mTestInput = valueInt;
1300             }
1301
1302             if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1303                 param.remove(String8("test_cmd_policy_format"));
1304                 int format = AudioSystem::INVALID_FORMAT;
1305                 if (value == "PCM 16 bits") {
1306                     format = AudioSystem::PCM_16_BIT;
1307                 } else if (value == "PCM 8 bits") {
1308                     format = AudioSystem::PCM_8_BIT;
1309                 } else if (value == "Compressed MP3") {
1310                     format = AudioSystem::MP3;
1311                 }
1312                 if (format != AudioSystem::INVALID_FORMAT) {
1313                     if (target == "Manager") {
1314                         mTestFormat = format;
1315                     } else if (mTestOutputs[mCurOutput] != 0) {
1316                         AudioParameter outputParam = AudioParameter();
1317                         outputParam.addInt(String8("format"), format);
1318                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1319                     }
1320                 }
1321             }
1322             if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1323                 param.remove(String8("test_cmd_policy_channels"));
1324                 int channels = 0;
1325
1326                 if (value == "Channels Stereo") {
1327                     channels =  AudioSystem::CHANNEL_OUT_STEREO;
1328                 } else if (value == "Channels Mono") {
1329                     channels =  AudioSystem::CHANNEL_OUT_MONO;
1330                 }
1331                 if (channels != 0) {
1332                     if (target == "Manager") {
1333                         mTestChannels = channels;
1334                     } else if (mTestOutputs[mCurOutput] != 0) {
1335                         AudioParameter outputParam = AudioParameter();
1336                         outputParam.addInt(String8("channels"), channels);
1337                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1338                     }
1339                 }
1340             }
1341             if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1342                 param.remove(String8("test_cmd_policy_sampleRate"));
1343                 if (valueInt >= 0 && valueInt <= 96000) {
1344                     int samplingRate = valueInt;
1345                     if (target == "Manager") {
1346                         mTestSamplingRate = samplingRate;
1347                     } else if (mTestOutputs[mCurOutput] != 0) {
1348                         AudioParameter outputParam = AudioParameter();
1349                         outputParam.addInt(String8("sampling_rate"), samplingRate);
1350                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1351                     }
1352                 }
1353             }
1354
1355             if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1356                 param.remove(String8("test_cmd_policy_reopen"));
1357
1358                 mpClientInterface->closeOutput(mPrimaryOutput);
1359                 delete mOutputs.valueFor(mPrimaryOutput);
1360                 mOutputs.removeItem(mPrimaryOutput);
1361
1362                 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1363                 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1364                 mPrimaryOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1365                                                 &outputDesc->mSamplingRate,
1366                                                 &outputDesc->mFormat,
1367                                                 &outputDesc->mChannels,
1368                                                 &outputDesc->mLatency,
1369                                                 outputDesc->mFlags);
1370                 if (mPrimaryOutput == 0) {
1371                     ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1372                             outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1373                 } else {
1374                     AudioParameter outputCmd = AudioParameter();
1375                     outputCmd.addInt(String8("set_id"), 0);
1376                     mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1377                     addOutput(mPrimaryOutput, outputDesc);
1378                 }
1379             }
1380
1381
1382             mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1383         }
1384     }
1385     return false;
1386 }
1387
1388 void AudioPolicyManagerBase::exit()
1389 {
1390     {
1391         AutoMutex _l(mLock);
1392         requestExit();
1393         mWaitWorkCV.signal();
1394     }
1395     requestExitAndWait();
1396 }
1397
1398 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1399 {
1400     for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1401         if (output == mTestOutputs[i]) return i;
1402     }
1403     return 0;
1404 }
1405 #endif //AUDIO_POLICY_TEST
1406
1407 // ---
1408
1409 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1410 {
1411     outputDesc->mId = id;
1412     mOutputs.add(id, outputDesc);
1413 }
1414
1415
1416 audio_io_handle_t AudioPolicyManagerBase::checkOutputForDevice(
1417                                                         audio_devices_t device,
1418                                                         AudioSystem::device_connection_state state)
1419 {
1420     audio_io_handle_t output = 0;
1421     AudioOutputDescriptor *outputDesc;
1422
1423     // TODO handle multiple outputs supporting overlapping sets of devices.
1424
1425     if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1426         // first check if one output already open can be routed to this device
1427         for (size_t i = 0; i < mOutputs.size(); i++) {
1428             AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1429             if (outputDesc->mProfile && outputDesc->mProfile->mSupportedDevices & device) {
1430                 return mOutputs.keyAt(i);
1431             }
1432         }
1433         // then look for one available output that can be routed to this device
1434         const IOProfile *outProfile = NULL;
1435         for (size_t i = 0; i < mOutputProfiles.size(); i++)
1436         {
1437             if (mOutputProfiles[i]->mSupportedDevices & device) {
1438                 outProfile = mOutputProfiles[i];
1439                 break;
1440             }
1441         }
1442         if (outProfile == NULL) {
1443             ALOGW("No output available for device %04x", device);
1444             return output;
1445         }
1446
1447         ALOGV("opening output for device %08x", device);
1448         outputDesc = new AudioOutputDescriptor(outProfile);
1449         outputDesc->mDevice = device;
1450         output = mpClientInterface->openOutput((uint32_t *)&outputDesc->mDevice,
1451                                                &outputDesc->mSamplingRate,
1452                                                &outputDesc->mFormat,
1453                                                &outputDesc->mChannels,
1454                                                &outputDesc->mLatency,
1455                                                outputDesc->mFlags);
1456
1457         if (output != 0) {
1458             audio_io_handle_t duplicatedOutput = 0;
1459             // add output descriptor
1460             addOutput(output, outputDesc);
1461             // set initial stream volume for device
1462             applyStreamVolumes(output, device);
1463
1464             //TODO: configure audio effect output stage here
1465
1466             // open a duplicating output thread for the new output and the primary output
1467             duplicatedOutput = mpClientInterface->openDuplicateOutput(output, mPrimaryOutput);
1468             if (duplicatedOutput != 0) {
1469                 // add duplicated output descriptor
1470                 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1471                 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1472                 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1473                 dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate;
1474                 dupOutputDesc->mFormat = outputDesc->mFormat;
1475                 dupOutputDesc->mChannels = outputDesc->mChannels;
1476                 dupOutputDesc->mLatency = outputDesc->mLatency;
1477                 addOutput(duplicatedOutput, dupOutputDesc);
1478                 applyStreamVolumes(duplicatedOutput, device);
1479             } else {
1480                 ALOGW("getOutput() could not open duplicated output for %d and %d",
1481                         mPrimaryOutput, output);
1482                 mpClientInterface->closeOutput(output);
1483                 mOutputs.removeItem(output);
1484                 delete outputDesc;
1485                 return 0;
1486             }
1487         } else {
1488             ALOGW("checkOutputForDevice() could not open output for device %x", device);
1489             delete outputDesc;
1490             return 0;
1491         }
1492     } else {
1493         // we assume that one given device is supported by zero or one output
1494         // check if one opened output is not needed any more after disconnecting one device
1495         for (size_t i = 0; i < mOutputs.size(); i++) {
1496             outputDesc = mOutputs.valueAt(i);
1497             if (outputDesc->mProfile &&
1498                     !(outputDesc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
1499                 output = mOutputs.keyAt(i);
1500                 break;
1501             }
1502         }
1503     }
1504
1505     return output;
1506 }
1507
1508 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
1509 {
1510     ALOGV("closeOutput(%d)", output);
1511
1512     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1513     if (outputDesc == NULL) {
1514         ALOGW("closeOutput() unknown output %d", output);
1515         return;
1516     }
1517
1518     // look for duplicated outputs connected to the output being removed.
1519     for (size_t i = 0; i < mOutputs.size(); i++) {
1520         AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
1521         if (dupOutputDesc->isDuplicated() &&
1522                 (dupOutputDesc->mOutput1 == outputDesc ||
1523                 dupOutputDesc->mOutput2 == outputDesc)) {
1524             AudioOutputDescriptor *outputDesc2;
1525             if (dupOutputDesc->mOutput1 == outputDesc) {
1526                 outputDesc2 = dupOutputDesc->mOutput2;
1527             } else {
1528                 outputDesc2 = dupOutputDesc->mOutput1;
1529             }
1530             // As all active tracks on duplicated output will be deleted,
1531             // and as they were also referenced on the other output, the reference
1532             // count for their stream type must be adjusted accordingly on
1533             // the other output.
1534             for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
1535                 int refCount = dupOutputDesc->mRefCount[j];
1536                 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
1537             }
1538             audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
1539             ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
1540
1541             mpClientInterface->closeOutput(duplicatedOutput);
1542             delete mOutputs.valueFor(duplicatedOutput);
1543             mOutputs.removeItem(duplicatedOutput);
1544         }
1545     }
1546
1547     AudioParameter param;
1548     param.add(String8("closing"), String8("true"));
1549     mpClientInterface->setParameters(output, param.toString());
1550
1551     mpClientInterface->closeOutput(output);
1552     delete mOutputs.valueFor(output);
1553     mOutputs.removeItem(output);
1554 }
1555
1556 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device)
1557 {
1558     SortedVector<audio_io_handle_t> outputs;
1559
1560     ALOGV("getOutputsForDevice() device %04x", device);
1561     for (size_t i = 0; i < mOutputs.size(); i++) {
1562         ALOGV("output %d isDuplicated=%d device=%04x",
1563                 i, mOutputs.valueAt(i)->isDuplicated(), mOutputs.valueAt(i)->supportedDevices());
1564         if ((device & mOutputs.valueAt(i)->supportedDevices()) == device) {
1565             ALOGV("getOutputsForDevice() found output %d", mOutputs.keyAt(i));
1566             outputs.add(mOutputs.keyAt(i));
1567         }
1568     }
1569     return outputs;
1570 }
1571
1572 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
1573                                    SortedVector<audio_io_handle_t>& outputs2)
1574 {
1575     if (outputs1.size() != outputs2.size()) {
1576         return false;
1577     }
1578     for (size_t i = 0; i < outputs1.size(); i++) {
1579         if (outputs1[i] != outputs2[i]) {
1580             return false;
1581         }
1582     }
1583     return true;
1584 }
1585
1586 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
1587 {
1588     SortedVector<audio_io_handle_t> srcOutputs =
1589             getOutputsForDevice(getDeviceForStrategy(strategy, true /*fromCache*/));
1590     SortedVector<audio_io_handle_t> dstOutputs =
1591             getOutputsForDevice(getDeviceForStrategy(strategy, false /*fromCache*/));
1592
1593     if (!vectorsEqual(srcOutputs,dstOutputs)) {
1594         // FIXME dstOutputs[0] happens to be the output to use, what guarantees it is always true?
1595         ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
1596               strategy, srcOutputs[0], dstOutputs[0]);
1597         // mute strategy while moving tracks from one output to another
1598         for (size_t i = 0; i < srcOutputs.size(); i++) {
1599             setStrategyMute(strategy, true, srcOutputs[i]);
1600             setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS);
1601         }
1602
1603         // Move effects associated to this strategy from previous output to new output
1604 //FIXME: removing this code works for effects applied to a particular session as they will be
1605 //       re-connected when the tracks are re-created after being invalidated.
1606 //       However we need to define a policy for global effects when more than one output is possible
1607 //        for (size_t i = 0; i < mEffects.size(); i++) {
1608 //            EffectDescriptor *desc = mEffects.valueAt(i);
1609 //            if (desc->mSession != AudioSystem::SESSION_OUTPUT_STAGE &&
1610 //                    desc->mStrategy == strategy &&
1611 //                    desc->mIo == srcOutputs[0]) {
1612 //                ALOGV("checkOutputForStrategy() moving effect %d to output %d",
1613 //                      mEffects.keyAt(i), dstOutputs[0]);
1614 //                mpClientInterface->moveEffects(desc->mSession, srcOutputs[0], dstOutputs[0]);
1615 //                desc->mIo = dstOutputs[0];
1616 //            }
1617 //        }
1618         // Move tracks associated to this strategy from previous output to new output
1619         for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1620             if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1621                 //FIXME see fixme on name change
1622                 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, dstOutputs[0]);
1623             }
1624         }
1625     }
1626 }
1627
1628 void AudioPolicyManagerBase::checkOutputForAllStrategies()
1629 {
1630     checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
1631     checkOutputForStrategy(STRATEGY_PHONE);
1632     checkOutputForStrategy(STRATEGY_SONIFICATION);
1633     checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
1634     checkOutputForStrategy(STRATEGY_MEDIA);
1635     checkOutputForStrategy(STRATEGY_DTMF);
1636 }
1637
1638 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
1639 {
1640     if (!mHasA2dp) {
1641         return 0;
1642     }
1643
1644     for (size_t i = 0; i < mOutputs.size(); i++) {
1645         AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1646         if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
1647             return mOutputs.keyAt(i);
1648         }
1649     }
1650
1651     return 0;
1652 }
1653
1654 void AudioPolicyManagerBase::checkA2dpSuspend()
1655 {
1656     if (!mHasA2dp) {
1657         return;
1658     }
1659     audio_io_handle_t a2dpOutput = getA2dpOutput();
1660     if (a2dpOutput == 0) {
1661         return;
1662     }
1663
1664     // suspend A2DP output if:
1665     //      (NOT already suspended) &&
1666     //      ((SCO device is connected &&
1667     //       (forced usage for communication || for record is SCO))) ||
1668     //      (phone state is ringing || in call)
1669     //
1670     // restore A2DP output if:
1671     //      (Already suspended) &&
1672     //      ((SCO device is NOT connected ||
1673     //       (forced usage NOT for communication && NOT for record is SCO))) &&
1674     //      (phone state is NOT ringing && NOT in call)
1675     //
1676     if (mA2dpSuspended) {
1677         if (((mScoDeviceAddress == "") ||
1678              ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1679               (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1680              ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1681               (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1682
1683             mpClientInterface->restoreOutput(a2dpOutput);
1684             mA2dpSuspended = false;
1685         }
1686     } else {
1687         if (((mScoDeviceAddress != "") &&
1688              ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1689               (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1690              ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1691               (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1692
1693             mpClientInterface->suspendOutput(a2dpOutput);
1694             mA2dpSuspended = true;
1695         }
1696     }
1697 }
1698
1699 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1700 {
1701     audio_devices_t device = (audio_devices_t)0;
1702
1703     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1704     // check the following by order of priority to request a routing change if necessary:
1705     // 1: the strategy enforced audible is active on the output:
1706     //      use device for strategy enforced audible
1707     // 2: we are in call or the strategy phone is active on the output:
1708     //      use device for strategy phone
1709     // 3: the strategy sonification is active on the output:
1710     //      use device for strategy sonification
1711     // 4: the strategy "respectful" sonification is active on the output:
1712     //      use device for strategy "respectful" sonification
1713     // 5: the strategy media is active on the output:
1714     //      use device for strategy media
1715     // 6: the strategy DTMF is active on the output:
1716     //      use device for strategy DTMF
1717     if (outputDesc->isUsedByStrategy(STRATEGY_ENFORCED_AUDIBLE)) {
1718         device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
1719     } else if (isInCall() ||
1720                     outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1721         device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1722     } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1723         device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1724     } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION_RESPECTFUL)) {
1725         device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
1726     } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1727         device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1728     } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1729         device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1730     }
1731
1732     ALOGV("getNewDevice() selected device %x", device);
1733     return device;
1734 }
1735
1736 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
1737     return (uint32_t)getStrategy(stream);
1738 }
1739
1740 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
1741     audio_devices_t devices;
1742     // By checking the range of stream before calling getStrategy, we avoid
1743     // getStrategy's behavior for invalid streams.  getStrategy would do a ALOGE
1744     // and then return STRATEGY_MEDIA, but we want to return the empty set.
1745     if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
1746         devices = (audio_devices_t)0;
1747     } else {
1748         AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
1749         devices = getDeviceForStrategy(strategy, true /*fromCache*/);
1750     }
1751     return devices;
1752 }
1753
1754 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
1755         AudioSystem::stream_type stream) {
1756     // stream to strategy mapping
1757     switch (stream) {
1758     case AudioSystem::VOICE_CALL:
1759     case AudioSystem::BLUETOOTH_SCO:
1760         return STRATEGY_PHONE;
1761     case AudioSystem::RING:
1762     case AudioSystem::ALARM:
1763         return STRATEGY_SONIFICATION;
1764     case AudioSystem::NOTIFICATION:
1765         return STRATEGY_SONIFICATION_RESPECTFUL;
1766     case AudioSystem::DTMF:
1767         return STRATEGY_DTMF;
1768     default:
1769         ALOGE("unknown stream type");
1770     case AudioSystem::SYSTEM:
1771         // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1772         // while key clicks are played produces a poor result
1773     case AudioSystem::TTS:
1774     case AudioSystem::MUSIC:
1775         return STRATEGY_MEDIA;
1776     case AudioSystem::ENFORCED_AUDIBLE:
1777         return STRATEGY_ENFORCED_AUDIBLE;
1778     }
1779 }
1780
1781 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
1782     switch(stream) {
1783     case AudioSystem::MUSIC:
1784         checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
1785         updateDeviceForStrategy();
1786         break;
1787     default:
1788         break;
1789     }
1790 }
1791
1792 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
1793                                                              bool fromCache)
1794 {
1795     uint32_t device = 0;
1796
1797     if (fromCache) {
1798         ALOGV("getDeviceForStrategy() from cache strategy %d, device %x",
1799               strategy, mDeviceForStrategy[strategy]);
1800         return mDeviceForStrategy[strategy];
1801     }
1802
1803     switch (strategy) {
1804
1805     case STRATEGY_SONIFICATION_RESPECTFUL:
1806         if (isInCall()) {
1807             device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
1808         } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
1809             // while media is playing (or has recently played), use the same device
1810             device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1811         } else {
1812             // when media is not playing anymore, fall back on the sonification behavior
1813             device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
1814         }
1815
1816         break;
1817
1818     case STRATEGY_DTMF:
1819         if (!isInCall()) {
1820             // when off call, DTMF strategy follows the same rules as MEDIA strategy
1821             device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1822             break;
1823         }
1824         // when in call, DTMF and PHONE strategies follow the same rules
1825         // FALL THROUGH
1826
1827     case STRATEGY_PHONE:
1828         // for phone strategy, we first consider the forced use and then the available devices by order
1829         // of priority
1830         switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
1831         case AudioSystem::FORCE_BT_SCO:
1832             if (!isInCall() || strategy != STRATEGY_DTMF) {
1833                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1834                 if (device) break;
1835             }
1836             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
1837             if (device) break;
1838             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
1839             if (device) break;
1840             // if SCO device is requested but no SCO device is available, fall back to default case
1841             // FALL THROUGH
1842
1843         default:    // FORCE_NONE
1844             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1845             if (device) break;
1846             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1847             if (device) break;
1848             // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
1849             if (mHasA2dp && !isInCall() && !mA2dpSuspended) {
1850                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1851                 if (device) break;
1852                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1853                 if (device) break;
1854             }
1855             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1856             if (device) break;
1857             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1858             if (device) break;
1859             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1860             if (device) break;
1861             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
1862             if (device) break;
1863             device = mDefaultOutputDevice;
1864             if (device == 0) {
1865                 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
1866             }
1867             break;
1868
1869         case AudioSystem::FORCE_SPEAKER:
1870             // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
1871             // A2DP speaker when forcing to speaker output
1872             if (mHasA2dp && !isInCall() && !mA2dpSuspended) {
1873                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1874                 if (device) break;
1875             }
1876             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1877             if (device) break;
1878             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1879             if (device) break;
1880             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1881             if (device) break;
1882             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1883             if (device) break;
1884             device = mDefaultOutputDevice;
1885             if (device == 0) {
1886                 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
1887             }
1888             break;
1889         }
1890     break;
1891
1892     case STRATEGY_SONIFICATION:
1893
1894         // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
1895         // handleIncallSonification().
1896         if (isInCall()) {
1897             device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
1898             break;
1899         }
1900         // FALL THROUGH
1901
1902     case STRATEGY_ENFORCED_AUDIBLE:
1903         // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
1904         // except when in call where it doesn't default to STRATEGY_PHONE behavior
1905
1906         device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1907         if (device == 0) {
1908             ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
1909         }
1910         // The second device used for sonification is the same as the device used by media strategy
1911         // FALL THROUGH
1912
1913     case STRATEGY_MEDIA: {
1914         uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1915         if (device2 == 0) {
1916             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1917         }
1918         if (mHasA2dp && (getA2dpOutput() != 0) && !mA2dpSuspended) {
1919             if (device2 == 0) {
1920                 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1921             }
1922             if (device2 == 0) {
1923                 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1924             }
1925             if (device2 == 0) {
1926                 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1927             }
1928         }
1929         if (device2 == 0) {
1930             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1931         }
1932         if (device2 == 0) {
1933             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1934         }
1935         if (device2 == 0) {
1936             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1937         }
1938         if (device2 == 0) {
1939             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1940         }
1941
1942         // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
1943         // STRATEGY_ENFORCED_AUDIBLE, 0 otherwise
1944         device |= device2;
1945         if (device) break;
1946         device = mDefaultOutputDevice;
1947         if (device == 0) {
1948             ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
1949         }
1950         } break;
1951
1952     default:
1953         ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
1954         break;
1955     }
1956
1957     ALOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
1958     return (audio_devices_t)device;
1959 }
1960
1961 void AudioPolicyManagerBase::updateDeviceForStrategy()
1962 {
1963     for (int i = 0; i < NUM_STRATEGIES; i++) {
1964         mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
1965     }
1966 }
1967
1968 void AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
1969                                                        uint32_t delayMs)
1970 {
1971     // mute/unmute strategies using an incompatible device combination
1972     // if muting, wait for the audio in pcm buffer to be drained before proceeding
1973     // if unmuting, unmute only after the specified delay
1974
1975     if (outputDesc->isDuplicated()) {
1976         return;
1977     }
1978
1979     uint32_t muteWaitMs = 0;
1980     audio_devices_t device = outputDesc->device();
1981     bool shouldMute = (outputDesc->refCount() != 0) &&
1982                     (AudioSystem::popCount(device) >= 2);
1983
1984     for (size_t i = 0; i < NUM_STRATEGIES; i++) {
1985         audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
1986         bool mute = shouldMute && (curDevice & device) && (curDevice != device);
1987         bool doMute = false;
1988
1989         if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
1990             doMute = true;
1991             outputDesc->mStrategyMutedByDevice[i] = true;
1992         } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
1993             doMute = true;
1994             outputDesc->mStrategyMutedByDevice[i] = false;
1995         }
1996         if (doMute) {
1997             for (size_t j = 0; j < mOutputs.size(); j++) {
1998                 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
1999                 if ((desc->supportedDevices() & outputDesc->supportedDevices()) == 0) {
2000                     continue;
2001                 }
2002                 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2003                 ALOGV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2004                       mute ? "muting" : "unmuting", i, curDevice, curOutput);
2005                 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2006                 if (mute && (desc->strategyRefCount((routing_strategy)i) != 0)) {
2007                     if (muteWaitMs < desc->latency()) {
2008                         muteWaitMs = desc->latency();
2009                     }
2010                 }
2011             }
2012         }
2013     }
2014
2015     // FIXME: should not need to double latency if volume could be applied immediately by the
2016     // audioflinger mixer. We must account for the delay between now and the next time
2017     // the audioflinger thread for this output will process a buffer (which corresponds to
2018     // one buffer size, usually 1/2 or 1/4 of the latency).
2019     muteWaitMs *= 2;
2020     // wait for the PCM output buffers to empty before proceeding with the rest of the command
2021     if (muteWaitMs > delayMs) {
2022         usleep((muteWaitMs - delayMs)*1000);
2023     }
2024 }
2025
2026 void AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2027                                              audio_devices_t device,
2028                                              bool force,
2029                                              int delayMs)
2030 {
2031     ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2032     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2033     AudioParameter param;
2034
2035     if (outputDesc->isDuplicated()) {
2036         setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2037         setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2038         return;
2039     }
2040     // filter devices according to output selected
2041     device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2042
2043     audio_devices_t prevDevice = outputDesc->mDevice;
2044
2045     ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2046
2047     if (device != 0) {
2048         outputDesc->mDevice = device;
2049     }
2050     checkDeviceMuteStrategies(outputDesc, delayMs);
2051
2052     // Do not change the routing if:
2053     //  - the requested device is 0
2054     //  - the requested device is the same as current device and force is not specified.
2055     // Doing this check here allows the caller to call setOutputDevice() without conditions
2056     if ((device == 0 || device == prevDevice) && !force) {
2057         ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2058         return;
2059     }
2060
2061     ALOGV("setOutputDevice() changing device");
2062     // do the routing
2063     param.addInt(String8(AudioParameter::keyRouting), (int)device);
2064     mpClientInterface->setParameters(output, param.toString(), delayMs);
2065
2066     // update stream volumes according to new device
2067     applyStreamVolumes(output, device, delayMs);
2068 }
2069
2070 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2071                                                    uint32_t samplingRate,
2072                                                    uint32_t format,
2073                                                    uint32_t channelMask)
2074 {
2075     IOProfile *inProfile = NULL;
2076
2077     // Choose an input profile based on the requested capture parameters: select the first available
2078     // profile supporting all requested parameters.
2079
2080     for (size_t i = 0; i < mInputProfiles.size(); i++)
2081     {
2082         IOProfile *profile = mInputProfiles[i];
2083         size_t j;
2084         if ((profile->mSupportedDevices & device) == 0) {
2085             continue;
2086         }
2087         for (j = 0; j < profile->mSamplingRates.size(); j++)
2088         {
2089             if (profile->mSamplingRates[j] == samplingRate) {
2090                 break;
2091             }
2092         }
2093         if (j == profile->mSamplingRates.size()) {
2094             continue;
2095         }
2096         for (j = 0; j < profile->mFormats.size(); j++)
2097         {
2098             if (profile->mFormats[j] == format) {
2099                 break;
2100             }
2101         }
2102         if (j == profile->mFormats.size()) {
2103             continue;
2104         }
2105         for (j = 0; j < profile->mChannelMasks.size(); j++)
2106         {
2107             if (profile->mChannelMasks[j] == channelMask) {
2108                 break;
2109             }
2110         }
2111         if (j == profile->mChannelMasks.size()) {
2112             continue;
2113         }
2114
2115         inProfile = profile;
2116         break;
2117     }
2118     ALOGW_IF(inProfile == NULL, "getInputProfile() no available input for device %04x"
2119             "samplingRate %d, format %d channel mask %04x",
2120              device,
2121              samplingRate,
2122              format,
2123              channelMask);
2124     return inProfile;
2125 }
2126
2127 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2128 {
2129     uint32_t device = 0;
2130
2131     switch(inputSource) {
2132     case AUDIO_SOURCE_DEFAULT:
2133     case AUDIO_SOURCE_MIC:
2134     case AUDIO_SOURCE_VOICE_RECOGNITION:
2135     case AUDIO_SOURCE_VOICE_COMMUNICATION:
2136         if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2137             mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2138             device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2139         } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
2140             device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
2141         } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BUILTIN_MIC) {
2142             device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
2143         }
2144         break;
2145     case AUDIO_SOURCE_CAMCORDER:
2146         if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BACK_MIC) {
2147             device = AudioSystem::DEVICE_IN_BACK_MIC;
2148         } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BUILTIN_MIC) {
2149             device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
2150         }
2151         break;
2152     case AUDIO_SOURCE_VOICE_UPLINK:
2153     case AUDIO_SOURCE_VOICE_DOWNLINK:
2154     case AUDIO_SOURCE_VOICE_CALL:
2155         if (mAvailableInputDevices & AudioSystem::DEVICE_IN_VOICE_CALL) {
2156             device = AudioSystem::DEVICE_IN_VOICE_CALL;
2157         }
2158         break;
2159     default:
2160         ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2161         break;
2162     }
2163     ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2164     return (audio_devices_t)device;
2165 }
2166
2167 audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
2168 {
2169     for (size_t i = 0; i < mInputs.size(); i++) {
2170         if (mInputs.valueAt(i)->mRefCount > 0) {
2171             return mInputs.keyAt(i);
2172         }
2173     }
2174     return 0;
2175 }
2176
2177
2178 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2179 {
2180     if (device == 0) {
2181         // this happens when forcing a route update and no track is active on an output.
2182         // In this case the returned category is not important.
2183         device =  AUDIO_DEVICE_OUT_SPEAKER;
2184     } else if (AudioSystem::popCount(device) > 1) {
2185         // Multiple device selection is either:
2186         //  - speaker + one other device: give priority to speaker in this case.
2187         //  - one A2DP device + another device: happens with duplicated output. In this case
2188         // retain the device on the A2DP output as the other must not correspond to an active
2189         // selection if not the speaker.
2190         if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2191             device = AUDIO_DEVICE_OUT_SPEAKER;
2192         } else {
2193             device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2194         }
2195     }
2196
2197     ALOGW_IF(AudioSystem::popCount(device) != 1,
2198             "getDeviceForVolume() invalid device combination: %08x",
2199             device);
2200
2201     return device;
2202 }
2203
2204 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
2205 {
2206     switch(getDeviceForVolume(device)) {
2207         case AUDIO_DEVICE_OUT_EARPIECE:
2208             return DEVICE_CATEGORY_EARPIECE;
2209         case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2210         case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2211         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2212         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2213         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2214         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2215             return DEVICE_CATEGORY_HEADSET;
2216         case AUDIO_DEVICE_OUT_SPEAKER:
2217         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
2218         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
2219         case AUDIO_DEVICE_OUT_AUX_DIGITAL:
2220         default:
2221             return DEVICE_CATEGORY_SPEAKER;
2222     }
2223 }
2224
2225 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
2226         int indexInUi)
2227 {
2228     device_category deviceCategory = getDeviceCategory(device);
2229     const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
2230
2231     // the volume index in the UI is relative to the min and max volume indices for this stream type
2232     int nbSteps = 1 + curve[VOLMAX].mIndex -
2233             curve[VOLMIN].mIndex;
2234     int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
2235             (streamDesc.mIndexMax - streamDesc.mIndexMin);
2236
2237     // find what part of the curve this index volume belongs to, or if it's out of bounds
2238     int segment = 0;
2239     if (volIdx < curve[VOLMIN].mIndex) {         // out of bounds
2240         return 0.0f;
2241     } else if (volIdx < curve[VOLKNEE1].mIndex) {
2242         segment = 0;
2243     } else if (volIdx < curve[VOLKNEE2].mIndex) {
2244         segment = 1;
2245     } else if (volIdx <= curve[VOLMAX].mIndex) {
2246         segment = 2;
2247     } else {                                                               // out of bounds
2248         return 1.0f;
2249     }
2250
2251     // linear interpolation in the attenuation table in dB
2252     float decibels = curve[segment].mDBAttenuation +
2253             ((float)(volIdx - curve[segment].mIndex)) *
2254                 ( (curve[segment+1].mDBAttenuation -
2255                         curve[segment].mDBAttenuation) /
2256                     ((float)(curve[segment+1].mIndex -
2257                             curve[segment].mIndex)) );
2258
2259     float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
2260
2261     ALOGV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
2262             curve[segment].mIndex, volIdx,
2263             curve[segment+1].mIndex,
2264             curve[segment].mDBAttenuation,
2265             decibels,
2266             curve[segment+1].mDBAttenuation,
2267             amplification);
2268
2269     return amplification;
2270 }
2271
2272 const AudioPolicyManagerBase::VolumeCurvePoint
2273     AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2274     {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
2275 };
2276
2277 const AudioPolicyManagerBase::VolumeCurvePoint
2278     AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2279     {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
2280 };
2281
2282 const AudioPolicyManagerBase::VolumeCurvePoint
2283     AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2284     {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2285 };
2286
2287 const AudioPolicyManagerBase::VolumeCurvePoint
2288     AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2289     {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2290 };
2291
2292
2293 const AudioPolicyManagerBase::VolumeCurvePoint
2294             *AudioPolicyManagerBase::sVolumeProfiles[AudioPolicyManagerBase::NUM_STRATEGIES]
2295                                                    [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2296     { // STRATEGY_MEDIA
2297         sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2298         sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2299         sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2300     },
2301     { // STRATEGY_PHONE
2302         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2303         sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2304         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2305     },
2306     { // STRATEGY_SONIFICATION
2307         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2308         sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2309         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2310     },
2311     { // STRATEGY_SONIFICATION_RESPECTFUL uses same volumes as SONIFICATION
2312         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2313         sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2314         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2315     },
2316     {  // STRATEGY_DTMF
2317         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2318         sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2319         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2320     },
2321     { // STRATEGY_ENFORCED_AUDIBLE
2322         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2323         sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2324         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2325     },
2326 };
2327
2328 void AudioPolicyManagerBase::initializeVolumeCurves()
2329 {
2330     for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2331         for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2332             mStreams[i].mVolumeCurve[j] =
2333                     sVolumeProfiles[getStrategy((AudioSystem::stream_type)i)][j];
2334         }
2335     }
2336 }
2337
2338 float AudioPolicyManagerBase::computeVolume(int stream,
2339                                             int index,
2340                                             audio_io_handle_t output,
2341                                             audio_devices_t device)
2342 {
2343     float volume = 1.0;
2344     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2345     StreamDescriptor &streamDesc = mStreams[stream];
2346
2347     if (device == 0) {
2348         device = outputDesc->device();
2349     }
2350
2351     // if volume is not 0 (not muted), force media volume to max on digital output
2352     if (stream == AudioSystem::MUSIC &&
2353         index != mStreams[stream].mIndexMin &&
2354         (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
2355         device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET)) {
2356         return 1.0;
2357     }
2358
2359     volume = volIndexToAmpl(device, streamDesc, index);
2360
2361     // if a headset is connected, apply the following rules to ring tones and notifications
2362     // to avoid sound level bursts in user's ears:
2363     // - always attenuate ring tones and notifications volume by 6dB
2364     // - if music is playing, always limit the volume to current music volume,
2365     // with a minimum threshold at -36dB so that notification is always perceived.
2366     const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2367     if ((device & (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
2368             AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
2369             AudioSystem::DEVICE_OUT_WIRED_HEADSET |
2370             AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) &&
2371         ((stream_strategy == STRATEGY_SONIFICATION)
2372                 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
2373                 || (stream == AudioSystem::SYSTEM)) &&
2374         streamDesc.mCanBeMuted) {
2375         volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
2376         // when the phone is ringing we must consider that music could have been paused just before
2377         // by the music application and behave as if music was active if the last music track was
2378         // just stopped
2379         if (outputDesc->mRefCount[AudioSystem::MUSIC] || mLimitRingtoneVolume) {
2380             float musicVol = computeVolume(AudioSystem::MUSIC,
2381                                mStreams[AudioSystem::MUSIC].getVolumeIndex(device),
2382                                output,
2383                                device);
2384             float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
2385                                 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
2386             if (volume > minVol) {
2387                 volume = minVol;
2388                 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
2389             }
2390         }
2391     }
2392
2393     return volume;
2394 }
2395
2396 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
2397                                                    int index,
2398                                                    audio_io_handle_t output,
2399                                                    audio_devices_t device,
2400                                                    int delayMs,
2401                                                    bool force)
2402 {
2403
2404     // do not change actual stream volume if the stream is muted
2405     if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
2406         ALOGV("checkAndSetVolume() stream %d muted count %d",
2407               stream, mOutputs.valueFor(output)->mMuteCount[stream]);
2408         return NO_ERROR;
2409     }
2410
2411     // do not change in call volume if bluetooth is connected and vice versa
2412     if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2413         (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
2414         ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
2415              stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
2416         return INVALID_OPERATION;
2417     }
2418
2419     float volume = computeVolume(stream, index, output, device);
2420     // We actually change the volume if:
2421     // - the float value returned by computeVolume() changed
2422     // - the force flag is set
2423     if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
2424             force) {
2425         mOutputs.valueFor(output)->mCurVolume[stream] = volume;
2426         ALOGV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
2427         if (stream == AudioSystem::VOICE_CALL ||
2428             stream == AudioSystem::DTMF ||
2429             stream == AudioSystem::BLUETOOTH_SCO) {
2430             // offset value to reflect actual hardware volume that never reaches 0
2431             // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
2432             volume = 0.01 + 0.99 * volume;
2433             // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
2434             // enabled
2435             if (stream == AudioSystem::BLUETOOTH_SCO) {
2436                 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
2437             }
2438         }
2439
2440         mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
2441     }
2442
2443     if (stream == AudioSystem::VOICE_CALL ||
2444         stream == AudioSystem::BLUETOOTH_SCO) {
2445         float voiceVolume;
2446         // Force voice volume to max for bluetooth SCO as volume is managed by the headset
2447         if (stream == AudioSystem::VOICE_CALL) {
2448             voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2449         } else {
2450             voiceVolume = 1.0;
2451         }
2452
2453         if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
2454             mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2455             mLastVoiceVolume = voiceVolume;
2456         }
2457     }
2458
2459     return NO_ERROR;
2460 }
2461
2462 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
2463                                                 audio_devices_t device,
2464                                                 int delayMs,
2465                                                 bool force)
2466 {
2467     ALOGV("applyStreamVolumes() for output %d and device %x", output, device);
2468
2469     for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2470         checkAndSetVolume(stream,
2471                           mStreams[stream].getVolumeIndex(device),
2472                           output,
2473                           device,
2474                           delayMs,
2475                           force);
2476     }
2477 }
2478
2479 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs)
2480 {
2481     ALOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
2482     for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2483         if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
2484             setStreamMute(stream, on, output, delayMs);
2485         }
2486     }
2487 }
2488
2489 void AudioPolicyManagerBase::setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs)
2490 {
2491     StreamDescriptor &streamDesc = mStreams[stream];
2492     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2493     audio_devices_t device = outputDesc->device();
2494
2495     ALOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, outputDesc->mMuteCount[stream]);
2496
2497     if (on) {
2498         if (outputDesc->mMuteCount[stream] == 0) {
2499             if (streamDesc.mCanBeMuted) {
2500                 checkAndSetVolume(stream, 0, output, device, delayMs);
2501             }
2502         }
2503         // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2504         outputDesc->mMuteCount[stream]++;
2505     } else {
2506         if (outputDesc->mMuteCount[stream] == 0) {
2507             ALOGW("setStreamMute() unmuting non muted stream!");
2508             return;
2509         }
2510         if (--outputDesc->mMuteCount[stream] == 0) {
2511             checkAndSetVolume(stream,
2512                               streamDesc.getVolumeIndex((audio_devices_t)device),
2513                               output,
2514                               device,
2515                               delayMs);
2516         }
2517     }
2518 }
2519
2520 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2521 {
2522     // if the stream pertains to sonification strategy and we are in call we must
2523     // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2524     // in the device used for phone strategy and play the tone if the selected device does not
2525     // interfere with the device used for phone strategy
2526     // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2527     // many times as there are active tracks on the output
2528     const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2529     if ((stream_strategy == STRATEGY_SONIFICATION) ||
2530             ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
2531         AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
2532         ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2533                 stream, starting, outputDesc->mDevice, stateChange);
2534         if (outputDesc->mRefCount[stream]) {
2535             int muteCount = 1;
2536             if (stateChange) {
2537                 muteCount = outputDesc->mRefCount[stream];
2538             }
2539             if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2540                 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2541                 for (int i = 0; i < muteCount; i++) {
2542                     setStreamMute(stream, starting, mPrimaryOutput);
2543                 }
2544             } else {
2545                 ALOGV("handleIncallSonification() high visibility");
2546                 if (outputDesc->device() &
2547                         getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
2548                     ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2549                     for (int i = 0; i < muteCount; i++) {
2550                         setStreamMute(stream, starting, mPrimaryOutput);
2551                     }
2552                 }
2553                 if (starting) {
2554                     mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2555                 } else {
2556                     mpClientInterface->stopTone();
2557                 }
2558             }
2559         }
2560     }
2561 }
2562
2563 bool AudioPolicyManagerBase::isInCall()
2564 {
2565     return isStateInCall(mPhoneState);
2566 }
2567
2568 bool AudioPolicyManagerBase::isStateInCall(int state) {
2569     return ((state == AudioSystem::MODE_IN_CALL) ||
2570             (state == AudioSystem::MODE_IN_COMMUNICATION));
2571 }
2572
2573 bool AudioPolicyManagerBase::needsDirectOuput(AudioSystem::stream_type stream,
2574                                     uint32_t samplingRate,
2575                                     uint32_t format,
2576                                     uint32_t channels,
2577                                     AudioSystem::output_flags flags,
2578                                     uint32_t device)
2579 {
2580    return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2581           (format != 0 && !AudioSystem::isLinearPCM(format)));
2582 }
2583
2584 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2585 {
2586     return MAX_EFFECTS_CPU_LOAD;
2587 }
2588
2589 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2590 {
2591     return MAX_EFFECTS_MEMORY;
2592 }
2593
2594 // --- AudioOutputDescriptor class implementation
2595
2596 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
2597         const IOProfile *profile)
2598     : mId(0), mSamplingRate(0), mFormat(0), mChannels(0), mLatency(0),
2599     mFlags((AudioSystem::output_flags)0), mDevice((audio_devices_t)0),
2600     mOutput1(0), mOutput2(0), mProfile(profile)
2601 {
2602     // clear usage count for all stream types
2603     for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2604         mRefCount[i] = 0;
2605         mCurVolume[i] = -1.0;
2606         mMuteCount[i] = 0;
2607         mStopTime[i] = 0;
2608     }
2609 }
2610
2611 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
2612 {
2613     if (isDuplicated()) {
2614         return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
2615     } else {
2616         return mDevice;
2617     }
2618 }
2619
2620 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
2621 {
2622     if (isDuplicated()) {
2623         return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
2624     } else {
2625         return mLatency;
2626     }
2627 }
2628
2629 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
2630         const AudioOutputDescriptor *outputDesc)
2631 {
2632     if (isDuplicated()) {
2633         return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
2634     } else if (outputDesc->isDuplicated()){
2635         return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
2636     } else {
2637         return strcmp(mProfile->mModuleName, outputDesc->mProfile->mModuleName) == 0;
2638     }
2639 }
2640
2641 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
2642 {
2643     // forward usage count change to attached outputs
2644     if (isDuplicated()) {
2645         mOutput1->changeRefCount(stream, delta);
2646         mOutput2->changeRefCount(stream, delta);
2647     }
2648     if ((delta + (int)mRefCount[stream]) < 0) {
2649         ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
2650         mRefCount[stream] = 0;
2651         return;
2652     }
2653     mRefCount[stream] += delta;
2654     ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
2655 }
2656
2657 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
2658 {
2659     uint32_t refcount = 0;
2660     for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2661         refcount += mRefCount[i];
2662     }
2663     return refcount;
2664 }
2665
2666 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
2667 {
2668     uint32_t refCount = 0;
2669     for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2670         if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2671             refCount += mRefCount[i];
2672         }
2673     }
2674     return refCount;
2675 }
2676
2677 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
2678 {
2679     if (isDuplicated()) {
2680         return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
2681     } else {
2682         return mProfile->mSupportedDevices ;
2683     }
2684 }
2685
2686 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
2687 {
2688     const size_t SIZE = 256;
2689     char buffer[SIZE];
2690     String8 result;
2691
2692     snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2693     result.append(buffer);
2694     snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2695     result.append(buffer);
2696     snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2697     result.append(buffer);
2698     snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
2699     result.append(buffer);
2700     snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
2701     result.append(buffer);
2702     snprintf(buffer, SIZE, " Devices %08x\n", device());
2703     result.append(buffer);
2704     snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
2705     result.append(buffer);
2706     for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2707         snprintf(buffer, SIZE, " %02d     %.03f     %02d       %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
2708         result.append(buffer);
2709     }
2710     write(fd, result.string(), result.size());
2711
2712     return NO_ERROR;
2713 }
2714
2715 // --- AudioInputDescriptor class implementation
2716
2717 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
2718     : mSamplingRate(0), mFormat(0), mChannels(0),
2719       mAcoustics((AudioSystem::audio_in_acoustics)0), mDevice((audio_devices_t)0), mRefCount(0),
2720       mInputSource(0), mProfile(profile)
2721 {
2722 }
2723
2724 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
2725 {
2726     const size_t SIZE = 256;
2727     char buffer[SIZE];
2728     String8 result;
2729
2730     snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2731     result.append(buffer);
2732     snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2733     result.append(buffer);
2734     snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2735     result.append(buffer);
2736     snprintf(buffer, SIZE, " Acoustics %08x\n", mAcoustics);
2737     result.append(buffer);
2738     snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
2739     result.append(buffer);
2740     snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
2741     result.append(buffer);
2742     write(fd, result.string(), result.size());
2743
2744     return NO_ERROR;
2745 }
2746
2747 // --- StreamDescriptor class implementation
2748
2749 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
2750     :   mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
2751 {
2752     mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
2753 }
2754
2755 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
2756 {
2757     device = AudioPolicyManagerBase::getDeviceForVolume(device);
2758     // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
2759     if (mIndexCur.indexOfKey(device) < 0) {
2760         device = AUDIO_DEVICE_OUT_DEFAULT;
2761     }
2762     return mIndexCur.valueFor(device);
2763 }
2764
2765 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
2766 {
2767     const size_t SIZE = 256;
2768     char buffer[SIZE];
2769     String8 result;
2770
2771     snprintf(buffer, SIZE, "%s         %02d         %02d         ",
2772              mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
2773     result.append(buffer);
2774     for (size_t i = 0; i < mIndexCur.size(); i++) {
2775         snprintf(buffer, SIZE, "%04x : %02d, ",
2776                  mIndexCur.keyAt(i),
2777                  mIndexCur.valueAt(i));
2778         result.append(buffer);
2779     }
2780     result.append("\n");
2781
2782     write(fd, result.string(), result.size());
2783 }
2784
2785 // --- EffectDescriptor class implementation
2786
2787 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
2788 {
2789     const size_t SIZE = 256;
2790     char buffer[SIZE];
2791     String8 result;
2792
2793     snprintf(buffer, SIZE, " I/O: %d\n", mIo);
2794     result.append(buffer);
2795     snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
2796     result.append(buffer);
2797     snprintf(buffer, SIZE, " Session: %d\n", mSession);
2798     result.append(buffer);
2799     snprintf(buffer, SIZE, " Name: %s\n",  mDesc.name);
2800     result.append(buffer);
2801     snprintf(buffer, SIZE, " %s\n",  mEnabled ? "Enabled" : "Disabled");
2802     result.append(buffer);
2803     write(fd, result.string(), result.size());
2804
2805     return NO_ERROR;
2806 }
2807
2808 // --- IOProfile class implementation
2809
2810 AudioPolicyManagerBase::IOProfile::IOProfile(const char *module)
2811     : mFlags((audio_policy_output_flags_t)0),
2812       mModuleName(strndup(module, AUDIO_HARDWARE_MODULE_ID_MAX_LEN))
2813 {
2814 }
2815
2816 AudioPolicyManagerBase::IOProfile::~IOProfile()
2817 {
2818     free(mModuleName);
2819 }
2820
2821 void AudioPolicyManagerBase::IOProfile::dump(int fd)
2822 {
2823     const size_t SIZE = 256;
2824     char buffer[SIZE];
2825     String8 result;
2826
2827     snprintf(buffer, SIZE, "  - sampling rates: ");
2828     result.append(buffer);
2829     for (size_t i = 0; i < mSamplingRates.size(); i++) {
2830         snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
2831         result.append(buffer);
2832         result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
2833     }
2834
2835     snprintf(buffer, SIZE, "  - channel masks: ");
2836     result.append(buffer);
2837     for (size_t i = 0; i < mChannelMasks.size(); i++) {
2838         snprintf(buffer, SIZE, "%04x", mChannelMasks[i]);
2839         result.append(buffer);
2840         result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
2841     }
2842
2843     snprintf(buffer, SIZE, "  - formats: ");
2844     result.append(buffer);
2845     for (size_t i = 0; i < mFormats.size(); i++) {
2846         snprintf(buffer, SIZE, "%d", mFormats[i]);
2847         result.append(buffer);
2848         result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
2849     }
2850
2851     snprintf(buffer, SIZE, "  - devices: %04x\n", mSupportedDevices);
2852     result.append(buffer);
2853     snprintf(buffer, SIZE, "  - flags: %04x\n", mFlags);
2854     result.append(buffer);
2855     snprintf(buffer, SIZE, "  - hw module: %s\n", mModuleName);
2856     result.append(buffer);
2857
2858     write(fd, result.string(), result.size());
2859 }
2860
2861 // --- audio_policy.conf file parsing
2862
2863 struct StringToEnum {
2864     const char *name;
2865     uint32_t value;
2866 };
2867
2868 #define STRING_TO_ENUM(string) { #string, string }
2869 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
2870
2871 const struct StringToEnum sDeviceNameToEnumTable[] = {
2872     STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
2873     STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
2874     STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
2875     STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
2876     STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
2877     STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
2878     STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
2879     STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
2880     STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
2881     STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
2882     STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
2883     STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
2884     STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
2885     STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
2886 };
2887
2888 const struct StringToEnum sFlagNameToEnumTable[] = {
2889     STRING_TO_ENUM(AUDIO_POLICY_OUTPUT_FLAG_DIRECT),
2890     STRING_TO_ENUM(AUDIO_POLICY_OUTPUT_FLAG_PRIMARY),
2891 };
2892
2893 const struct StringToEnum sFormatNameToEnumTable[] = {
2894     STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
2895     STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
2896     STRING_TO_ENUM(AUDIO_FORMAT_MP3),
2897     STRING_TO_ENUM(AUDIO_FORMAT_AAC),
2898     STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
2899 };
2900
2901 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
2902     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
2903     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
2904     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
2905     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
2906 };
2907
2908 const struct StringToEnum sInChannelsNameToEnumTable[] = {
2909     STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
2910     STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
2911 };
2912
2913
2914 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
2915                                               size_t size,
2916                                               const char *name)
2917 {
2918     for (size_t i = 0; i < size; i++) {
2919         if (strcmp(table[i].name, name) == 0) {
2920             ALOGV("stringToEnum() found %s", table[i].name);
2921             return table[i].value;
2922         }
2923     }
2924     return 0;
2925 }
2926
2927 audio_policy_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
2928 {
2929     uint32_t flag = 0;
2930
2931     // it is OK to cast name to non const here as we are not going to use it after
2932     // strtok() modifies it
2933     char *flagName = strtok(name, "|");
2934     while (flagName != NULL) {
2935         if (strlen(flagName) != 0) {
2936             flag |= stringToEnum(sFlagNameToEnumTable,
2937                                ARRAY_SIZE(sFlagNameToEnumTable),
2938                                flagName);
2939         }
2940         flagName = strtok(NULL, "|");
2941     }
2942     return (audio_policy_output_flags_t)flag;
2943 }
2944
2945 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
2946 {
2947     uint32_t device = 0;
2948
2949     char *devName = strtok(name, "|");
2950     while (devName != NULL) {
2951         if (strlen(devName) != 0) {
2952             device |= stringToEnum(sDeviceNameToEnumTable,
2953                                  ARRAY_SIZE(sDeviceNameToEnumTable),
2954                                  devName);
2955         }
2956         devName = strtok(NULL, "|");
2957     }
2958     return (audio_devices_t)device;
2959 }
2960
2961 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
2962 {
2963     char *str = strtok(name, "|");
2964
2965     while (str != NULL) {
2966         uint32_t rate = atoi(str);
2967         if (rate != 0) {
2968             ALOGV("loadSamplingRates() adding rate %d", rate);
2969             profile->mSamplingRates.add(rate);
2970         }
2971         str = strtok(NULL, "|");
2972     }
2973     return;
2974 }
2975
2976 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
2977 {
2978     char *str = strtok(name, "|");
2979
2980     while (str != NULL) {
2981         audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
2982                                                              ARRAY_SIZE(sFormatNameToEnumTable),
2983                                                              str);
2984         if (format != 0) {
2985             profile->mFormats.add(format);
2986         }
2987         str = strtok(NULL, "|");
2988     }
2989     return;
2990 }
2991
2992 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
2993 {
2994     const char *str = strtok(name, "|");
2995
2996     ALOGV("loadInChannels() %s", name);
2997     while (str != NULL) {
2998         audio_channel_mask_t channelMask =
2999                 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
3000                                                    ARRAY_SIZE(sInChannelsNameToEnumTable),
3001                                                    str);
3002         if (channelMask != 0) {
3003             ALOGV("loadInChannels() adding channelMask %04x", channelMask);
3004             profile->mChannelMasks.add(channelMask);
3005         }
3006         str = strtok(NULL, "|");
3007     }
3008     return;
3009 }
3010
3011 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
3012 {
3013     const char *str = strtok(name, "|");
3014     audio_channel_mask_t channelMask;
3015
3016     while (str != NULL) {
3017         channelMask = stringToEnum(sOutChannelsNameToEnumTable,
3018                             ARRAY_SIZE(sOutChannelsNameToEnumTable),
3019                             str);
3020         if (channelMask != 0) {
3021             profile->mChannelMasks.add(channelMask);
3022         }
3023         str = strtok(NULL, "|");
3024     }
3025     return;
3026 }
3027
3028 status_t AudioPolicyManagerBase::loadInput(cnode *root, const char *module)
3029 {
3030     cnode *node = root->first_child;
3031
3032     IOProfile *profile = new IOProfile(module);
3033
3034     while (node) {
3035         if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3036             loadSamplingRates((char *)node->value, profile);
3037         } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3038             loadFormats((char *)node->value, profile);
3039         } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3040             loadInChannels((char *)node->value, profile);
3041         } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3042             profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3043         }
3044         node = node->next;
3045     }
3046     ALOGW_IF(profile->mSupportedDevices == (audio_devices_t)0,
3047             "loadInput() invalid supported devices");
3048     ALOGW_IF(profile->mChannelMasks.size() == 0,
3049             "loadInput() invalid supported channel masks");
3050     ALOGW_IF(profile->mSamplingRates.size() == 0,
3051             "loadInput() invalid supported sampling rates");
3052     ALOGW_IF(profile->mFormats.size() == 0,
3053             "loadInput() invalid supported formats");
3054     if ((profile->mSupportedDevices != (audio_devices_t)0) &&
3055             (profile->mChannelMasks.size() != 0) &&
3056             (profile->mSamplingRates.size() != 0) &&
3057             (profile->mFormats.size() != 0)) {
3058
3059         ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
3060
3061         mInputProfiles.add(profile);
3062         return NO_ERROR;
3063     } else {
3064         delete profile;
3065         return BAD_VALUE;
3066     }
3067 }
3068
3069 status_t AudioPolicyManagerBase::loadOutput(cnode *root, const char *module)
3070 {
3071     cnode *node = root->first_child;
3072
3073     IOProfile *profile = new IOProfile(module);
3074
3075     while (node) {
3076         if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3077             loadSamplingRates((char *)node->value, profile);
3078         } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3079             loadFormats((char *)node->value, profile);
3080         } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3081             loadOutChannels((char *)node->value, profile);
3082         } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3083             profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3084         } else if (strcmp(node->name, FLAGS_TAG) == 0) {
3085             profile->mFlags = parseFlagNames((char *)node->value);
3086         }
3087         node = node->next;
3088     }
3089     ALOGW_IF(profile->mSupportedDevices == (audio_devices_t)0,
3090             "loadOutput() invalid supported devices");
3091     ALOGW_IF(profile->mChannelMasks.size() == 0,
3092             "loadOutput() invalid supported channel masks");
3093     ALOGW_IF(profile->mSamplingRates.size() == 0,
3094             "loadOutput() invalid supported sampling rates");
3095     ALOGW_IF(profile->mFormats.size() == 0,
3096             "loadOutput() invalid supported formats");
3097     if ((profile->mSupportedDevices != (audio_devices_t)0) &&
3098             (profile->mChannelMasks.size() != 0) &&
3099             (profile->mSamplingRates.size() != 0) &&
3100             (profile->mFormats.size() != 0)) {
3101
3102         ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
3103               profile->mSupportedDevices, profile->mFlags);
3104
3105         mOutputProfiles.add(profile);
3106         return NO_ERROR;
3107     } else {
3108         delete profile;
3109         return BAD_VALUE;
3110     }
3111 }
3112
3113 void AudioPolicyManagerBase::loadHwModule(cnode *root)
3114 {
3115     cnode *node = config_find(root, OUTPUTS_TAG);
3116     status_t status = NAME_NOT_FOUND;
3117     if (node != NULL) {
3118         if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
3119             mHasA2dp = true;
3120         }
3121         node = node->first_child;
3122         while (node) {
3123             ALOGV("loadHwModule() loading output %s", node->name);
3124             status_t tmpStatus = loadOutput(node, root->name);
3125             if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3126                 status = tmpStatus;
3127             }
3128             node = node->next;
3129         }
3130     }
3131     node = config_find(root, INPUTS_TAG);
3132     if (node != NULL) {
3133         node = node->first_child;
3134         while (node) {
3135             ALOGV("loadHwModule() loading input %s", node->name);
3136             status_t tmpStatus = loadInput(node, root->name);
3137             if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3138                 status = tmpStatus;
3139             }
3140             node = node->next;
3141         }
3142     }
3143     if (status == NO_ERROR) {
3144         //TODO: load HW module via audioflinger
3145     }
3146 }
3147
3148 void AudioPolicyManagerBase::loadHwModules(cnode *root)
3149 {
3150     cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
3151     if (node == NULL) {
3152         return;
3153     }
3154
3155     node = node->first_child;
3156     while (node) {
3157         ALOGV("loadHwModules() loading module %s", node->name);
3158         loadHwModule(node);
3159         node = node->next;
3160     }
3161 }
3162
3163 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
3164 {
3165     cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
3166     if (node == NULL) {
3167         return;
3168     }
3169     node = node->first_child;
3170     while (node) {
3171         if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
3172             mAttachedOutputDevices = parseDeviceNames((char *)node->value);
3173             ALOGW_IF(mAttachedOutputDevices == 0, "loadGlobalConfig() no attached output devices");
3174             ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
3175         } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
3176             mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
3177                                               ARRAY_SIZE(sDeviceNameToEnumTable),
3178                                               (char *)node->value);
3179             ALOGW_IF(mDefaultOutputDevice == 0, "loadGlobalConfig() default device not specified");
3180             ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
3181         } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
3182             mAvailableInputDevices = parseDeviceNames((char *)node->value);
3183             ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
3184         }
3185         node = node->next;
3186     }
3187 }
3188
3189 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
3190 {
3191     cnode *root;
3192     char *data;
3193
3194     data = (char *)load_file(path, NULL);
3195     if (data == NULL) {
3196         return -ENODEV;
3197     }
3198     root = config_node("", "");
3199     config_load(root, data);
3200
3201     loadGlobalConfig(root);
3202     loadHwModules(root);
3203
3204     config_free(root);
3205     free(root);
3206     free(data);
3207
3208     return NO_ERROR;
3209 }
3210
3211
3212 }; // namespace android