OSDN Git Service

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