AudioService.java revision a25c5d88d17f251262307ce31e799c9cf361d145
1/*
2 * Copyright (C) 2006 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
17package android.media;
18
19import android.app.ActivityManagerNative;
20import android.bluetooth.BluetoothA2dp;
21import android.bluetooth.BluetoothAdapter;
22import android.bluetooth.BluetoothClass;
23import android.bluetooth.BluetoothDevice;
24import android.bluetooth.BluetoothHeadset;
25import android.bluetooth.BluetoothProfile;
26import android.content.BroadcastReceiver;
27import android.content.ComponentName;
28import android.content.ContentResolver;
29import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
33import android.database.ContentObserver;
34import android.media.MediaPlayer.OnCompletionListener;
35import android.media.MediaPlayer.OnErrorListener;
36import android.os.Binder;
37import android.os.Environment;
38import android.os.Handler;
39import android.os.IBinder;
40import android.os.Looper;
41import android.os.Message;
42import android.os.RemoteException;
43import android.os.ServiceManager;
44import android.os.SystemProperties;
45import android.provider.Settings;
46import android.provider.Settings.System;
47import android.telephony.PhoneStateListener;
48import android.telephony.TelephonyManager;
49import android.util.Log;
50import android.view.KeyEvent;
51import android.view.VolumePanel;
52
53import com.android.internal.telephony.ITelephony;
54
55import java.io.FileDescriptor;
56import java.io.IOException;
57import java.io.PrintWriter;
58import java.util.ArrayList;
59import java.util.HashMap;
60import java.util.Iterator;
61import java.util.List;
62import java.util.Map;
63import java.util.NoSuchElementException;
64import java.util.Set;
65import java.util.Stack;
66
67/**
68 * The implementation of the volume manager service.
69 * <p>
70 * This implementation focuses on delivering a responsive UI. Most methods are
71 * asynchronous to external calls. For example, the task of setting a volume
72 * will update our internal state, but in a separate thread will set the system
73 * volume and later persist to the database. Similarly, setting the ringer mode
74 * will update the state and broadcast a change and in a separate thread later
75 * persist the ringer mode.
76 *
77 * @hide
78 */
79public class AudioService extends IAudioService.Stub {
80
81    private static final String TAG = "AudioService";
82
83    /** How long to delay before persisting a change in volume/ringer mode. */
84    private static final int PERSIST_DELAY = 3000;
85
86    private Context mContext;
87    private ContentResolver mContentResolver;
88    private boolean mVoiceCapable;
89
90    /** The UI */
91    private VolumePanel mVolumePanel;
92
93    // sendMsg() flags
94    /** Used when a message should be shared across all stream types. */
95    private static final int SHARED_MSG = -1;
96    /** If the msg is already queued, replace it with this one. */
97    private static final int SENDMSG_REPLACE = 0;
98    /** If the msg is already queued, ignore this one and leave the old. */
99    private static final int SENDMSG_NOOP = 1;
100    /** If the msg is already queued, queue this one and leave the old. */
101    private static final int SENDMSG_QUEUE = 2;
102
103    // AudioHandler message.whats
104    private static final int MSG_SET_SYSTEM_VOLUME = 0;
105    private static final int MSG_PERSIST_VOLUME = 1;
106    private static final int MSG_PERSIST_RINGER_MODE = 3;
107    private static final int MSG_PERSIST_VIBRATE_SETTING = 4;
108    private static final int MSG_MEDIA_SERVER_DIED = 5;
109    private static final int MSG_MEDIA_SERVER_STARTED = 6;
110    private static final int MSG_PLAY_SOUND_EFFECT = 7;
111    private static final int MSG_BTA2DP_DOCK_TIMEOUT = 8;
112    private static final int MSG_LOAD_SOUND_EFFECTS = 9;
113
114    private static final int BTA2DP_DOCK_TIMEOUT_MILLIS = 8000;
115
116    /** @see AudioSystemThread */
117    private AudioSystemThread mAudioSystemThread;
118    /** @see AudioHandler */
119    private AudioHandler mAudioHandler;
120    /** @see VolumeStreamState */
121    private VolumeStreamState[] mStreamStates;
122    private SettingsObserver mSettingsObserver;
123
124    private int mMode;
125    private Object mSettingsLock = new Object();
126    private boolean mMediaServerOk;
127
128    private SoundPool mSoundPool;
129    private Object mSoundEffectsLock = new Object();
130    private static final int NUM_SOUNDPOOL_CHANNELS = 4;
131    private static final int SOUND_EFFECT_VOLUME = 1000;
132
133    /* Sound effect file names  */
134    private static final String SOUND_EFFECTS_PATH = "/media/audio/ui/";
135    private static final String[] SOUND_EFFECT_FILES = new String[] {
136        "Effect_Tick.ogg",
137        "KeypressStandard.ogg",
138        "KeypressSpacebar.ogg",
139        "KeypressDelete.ogg",
140        "KeypressReturn.ogg"
141    };
142
143    /* Sound effect file name mapping sound effect id (AudioManager.FX_xxx) to
144     * file index in SOUND_EFFECT_FILES[] (first column) and indicating if effect
145     * uses soundpool (second column) */
146    private int[][] SOUND_EFFECT_FILES_MAP = new int[][] {
147        {0, -1},  // FX_KEY_CLICK
148        {0, -1},  // FX_FOCUS_NAVIGATION_UP
149        {0, -1},  // FX_FOCUS_NAVIGATION_DOWN
150        {0, -1},  // FX_FOCUS_NAVIGATION_LEFT
151        {0, -1},  // FX_FOCUS_NAVIGATION_RIGHT
152        {1, -1},  // FX_KEYPRESS_STANDARD
153        {2, -1},  // FX_KEYPRESS_SPACEBAR
154        {3, -1},  // FX_FOCUS_DELETE
155        {4, -1}   // FX_FOCUS_RETURN
156    };
157
158   /** @hide Maximum volume index values for audio streams */
159    private int[] MAX_STREAM_VOLUME = new int[] {
160        5,  // STREAM_VOICE_CALL
161        7,  // STREAM_SYSTEM
162        7,  // STREAM_RING
163        15, // STREAM_MUSIC
164        7,  // STREAM_ALARM
165        7,  // STREAM_NOTIFICATION
166        15, // STREAM_BLUETOOTH_SCO
167        7,  // STREAM_SYSTEM_ENFORCED
168        15, // STREAM_DTMF
169        15  // STREAM_TTS
170    };
171    /* STREAM_VOLUME_ALIAS[] indicates for each stream if it uses the volume settings
172     * of another stream: This avoids multiplying the volume settings for hidden
173     * stream types that follow other stream behavior for volume settings
174     * NOTE: do not create loops in aliases! */
175    private int[] STREAM_VOLUME_ALIAS = new int[] {
176        AudioSystem.STREAM_VOICE_CALL,  // STREAM_VOICE_CALL
177        AudioSystem.STREAM_SYSTEM,  // STREAM_SYSTEM
178        AudioSystem.STREAM_RING,  // STREAM_RING
179        AudioSystem.STREAM_MUSIC, // STREAM_MUSIC
180        AudioSystem.STREAM_ALARM,  // STREAM_ALARM
181        AudioSystem.STREAM_NOTIFICATION,  // STREAM_NOTIFICATION
182        AudioSystem.STREAM_BLUETOOTH_SCO, // STREAM_BLUETOOTH_SCO
183        AudioSystem.STREAM_SYSTEM,  // STREAM_SYSTEM_ENFORCED
184        AudioSystem.STREAM_VOICE_CALL, // STREAM_DTMF
185        AudioSystem.STREAM_MUSIC  // STREAM_TTS
186    };
187
188    private AudioSystem.ErrorCallback mAudioSystemCallback = new AudioSystem.ErrorCallback() {
189        public void onError(int error) {
190            switch (error) {
191            case AudioSystem.AUDIO_STATUS_SERVER_DIED:
192                if (mMediaServerOk) {
193                    sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
194                            null, 1500);
195                    mMediaServerOk = false;
196                }
197                break;
198            case AudioSystem.AUDIO_STATUS_OK:
199                if (!mMediaServerOk) {
200                    sendMsg(mAudioHandler, MSG_MEDIA_SERVER_STARTED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
201                            null, 0);
202                    mMediaServerOk = true;
203                }
204                break;
205            default:
206                break;
207            }
208       }
209    };
210
211    /**
212     * Current ringer mode from one of {@link AudioManager#RINGER_MODE_NORMAL},
213     * {@link AudioManager#RINGER_MODE_SILENT}, or
214     * {@link AudioManager#RINGER_MODE_VIBRATE}.
215     */
216    private int mRingerMode;
217
218    /** @see System#MODE_RINGER_STREAMS_AFFECTED */
219    private int mRingerModeAffectedStreams;
220
221    // Streams currently muted by ringer mode
222    private int mRingerModeMutedStreams;
223
224    /** @see System#MUTE_STREAMS_AFFECTED */
225    private int mMuteAffectedStreams;
226
227    /**
228     * Has multiple bits per vibrate type to indicate the type's vibrate
229     * setting. See {@link #setVibrateSetting(int, int)}.
230     * <p>
231     * NOTE: This is not the final decision of whether vibrate is on/off for the
232     * type since it depends on the ringer mode. See {@link #shouldVibrate(int)}.
233     */
234    private int mVibrateSetting;
235
236    /** @see System#NOTIFICATIONS_USE_RING_VOLUME */
237    private int mNotificationsUseRingVolume;
238
239    // Broadcast receiver for device connections intent broadcasts
240    private final BroadcastReceiver mReceiver = new AudioServiceBroadcastReceiver();
241
242    //  Broadcast receiver for media button broadcasts (separate from mReceiver to
243    //  independently change its priority)
244    private final BroadcastReceiver mMediaButtonReceiver = new MediaButtonBroadcastReceiver();
245
246    // Used to alter media button redirection when the phone is ringing.
247    private boolean mIsRinging = false;
248
249    // Devices currently connected
250    private HashMap <Integer, String> mConnectedDevices = new HashMap <Integer, String>();
251
252    // Forced device usage for communications
253    private int mForcedUseForComm;
254
255    // List of binder death handlers for setMode() client processes.
256    // The last process to have called setMode() is at the top of the list.
257    private ArrayList <SetModeDeathHandler> mSetModeDeathHandlers = new ArrayList <SetModeDeathHandler>();
258
259    // List of clients having issued a SCO start request
260    private ArrayList <ScoClient> mScoClients = new ArrayList <ScoClient>();
261
262    // BluetoothHeadset API to control SCO connection
263    private BluetoothHeadset mBluetoothHeadset;
264
265    // Bluetooth headset device
266    private BluetoothDevice mBluetoothHeadsetDevice;
267
268    // Indicate if SCO audio connection is currently active and if the initiator is
269    // audio service (internal) or bluetooth headset (external)
270    private int mScoAudioState;
271    // SCO audio state is not active
272    private static final int SCO_STATE_INACTIVE = 0;
273    // SCO audio state is active or starting due to a local request to start a virtual call
274    private static final int SCO_STATE_ACTIVE_INTERNAL = 1;
275    // SCO audio state is active due to an action in BT handsfree (either voice recognition or
276    // in call audio)
277    private static final int SCO_STATE_ACTIVE_EXTERNAL = 2;
278
279    // true if boot sequence has been completed
280    private boolean mBootCompleted;
281    // listener for SoundPool sample load completion indication
282    private SoundPoolCallback mSoundPoolCallBack;
283    // thread for SoundPool listener
284    private SoundPoolListenerThread mSoundPoolListenerThread;
285    // message looper for SoundPool listener
286    private Looper mSoundPoolLooper = null;
287    // default volume applied to sound played with playSoundEffect()
288    private static final int SOUND_EFFECT_DEFAULT_VOLUME_DB = -20;
289    // volume applied to sound played with playSoundEffect() read from ro.config.sound_fx_volume
290    private int SOUND_EFFECT_VOLUME_DB;
291    // getActiveStreamType() will return STREAM_NOTIFICATION during this period after a notification
292    // stopped
293    private static final int NOTIFICATION_VOLUME_DELAY_MS = 5000;
294    // previous volume adjustment direction received by checkForRingerModeChange()
295    private int mPrevVolDirection = AudioManager.ADJUST_SAME;
296
297    ///////////////////////////////////////////////////////////////////////////
298    // Construction
299    ///////////////////////////////////////////////////////////////////////////
300
301    /** @hide */
302    public AudioService(Context context) {
303        mContext = context;
304        mContentResolver = context.getContentResolver();
305        mVoiceCapable = mContext.getResources().getBoolean(
306                com.android.internal.R.bool.config_voice_capable);
307
308       // Intialized volume
309        MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = SystemProperties.getInt(
310            "ro.config.vc_call_vol_steps",
311           MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]);
312
313        SOUND_EFFECT_VOLUME_DB = SystemProperties.getInt(
314                "ro.config.sound_fx_volume",
315                SOUND_EFFECT_DEFAULT_VOLUME_DB);
316
317        mVolumePanel = new VolumePanel(context, this);
318        mSettingsObserver = new SettingsObserver();
319        mForcedUseForComm = AudioSystem.FORCE_NONE;
320        createAudioSystemThread();
321        readPersistedSettings();
322        createStreamStates();
323        // Call setMode() to initialize mSetModeDeathHandlers
324        mMode = AudioSystem.MODE_INVALID;
325        setMode(AudioSystem.MODE_NORMAL, null);
326        mMediaServerOk = true;
327
328        // Call setRingerModeInt() to apply correct mute
329        // state on streams affected by ringer mode.
330        mRingerModeMutedStreams = 0;
331        setRingerModeInt(getRingerMode(), false);
332
333        AudioSystem.setErrorCallback(mAudioSystemCallback);
334
335        mBluetoothHeadsetDevice = null;
336        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
337        if (adapter != null) {
338            adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
339                                    BluetoothProfile.HEADSET);
340        }
341
342        // Register for device connection intent broadcasts.
343        IntentFilter intentFilter =
344                new IntentFilter(Intent.ACTION_HEADSET_PLUG);
345
346        intentFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
347        intentFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
348        intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
349        intentFilter.addAction(Intent.ACTION_DOCK_EVENT);
350        intentFilter.addAction(Intent.ACTION_USB_ANLG_HEADSET_PLUG);
351        intentFilter.addAction(Intent.ACTION_USB_DGTL_HEADSET_PLUG);
352        intentFilter.addAction(Intent.ACTION_HDMI_AUDIO_PLUG);
353        intentFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
354        context.registerReceiver(mReceiver, intentFilter);
355
356        // Register for media button intent broadcasts.
357        intentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
358        intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
359        context.registerReceiver(mMediaButtonReceiver, intentFilter);
360
361        // Register for phone state monitoring
362        TelephonyManager tmgr = (TelephonyManager)
363                context.getSystemService(Context.TELEPHONY_SERVICE);
364        tmgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
365    }
366
367    private void createAudioSystemThread() {
368        mAudioSystemThread = new AudioSystemThread();
369        mAudioSystemThread.start();
370        waitForAudioHandlerCreation();
371    }
372
373    /** Waits for the volume handler to be created by the other thread. */
374    private void waitForAudioHandlerCreation() {
375        synchronized(this) {
376            while (mAudioHandler == null) {
377                try {
378                    // Wait for mAudioHandler to be set by the other thread
379                    wait();
380                } catch (InterruptedException e) {
381                    Log.e(TAG, "Interrupted while waiting on volume handler.");
382                }
383            }
384        }
385    }
386
387    private void createStreamStates() {
388        int numStreamTypes = AudioSystem.getNumStreamTypes();
389        VolumeStreamState[] streams = mStreamStates = new VolumeStreamState[numStreamTypes];
390
391        for (int i = 0; i < numStreamTypes; i++) {
392            streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[i]], i);
393        }
394
395        // Correct stream index values for streams with aliases
396        for (int i = 0; i < numStreamTypes; i++) {
397            if (STREAM_VOLUME_ALIAS[i] != i) {
398                int index = rescaleIndex(streams[i].mIndex, STREAM_VOLUME_ALIAS[i], i);
399                streams[i].mIndex = streams[i].getValidIndex(index);
400                setStreamVolumeIndex(i, index);
401                index = rescaleIndex(streams[i].mLastAudibleIndex, STREAM_VOLUME_ALIAS[i], i);
402                streams[i].mLastAudibleIndex = streams[i].getValidIndex(index);
403            }
404        }
405    }
406
407    private void readPersistedSettings() {
408        final ContentResolver cr = mContentResolver;
409
410        mRingerMode = System.getInt(cr, System.MODE_RINGER, AudioManager.RINGER_MODE_NORMAL);
411
412        mVibrateSetting = System.getInt(cr, System.VIBRATE_ON, 0);
413
414        mRingerModeAffectedStreams = Settings.System.getInt(cr,
415                Settings.System.MODE_RINGER_STREAMS_AFFECTED,
416                ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)|
417                 (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED)|
418                 (1 << AudioSystem.STREAM_MUSIC)));
419
420        if (!mVoiceCapable) {
421            mRingerModeAffectedStreams |= (1 << AudioSystem.STREAM_MUSIC);
422        }
423        mMuteAffectedStreams = System.getInt(cr,
424                System.MUTE_STREAMS_AFFECTED,
425                ((1 << AudioSystem.STREAM_MUSIC)|(1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_SYSTEM)));
426
427        if (mVoiceCapable) {
428            mNotificationsUseRingVolume = System.getInt(cr,
429                    Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 1);
430        } else {
431            mNotificationsUseRingVolume = 1;
432        }
433
434        if (mNotificationsUseRingVolume == 1) {
435            STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING;
436        }
437        // Each stream will read its own persisted settings
438
439        // Broadcast the sticky intent
440        broadcastRingerMode();
441
442        // Broadcast vibrate settings
443        broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);
444        broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION);
445    }
446
447    private void setStreamVolumeIndex(int stream, int index) {
448        AudioSystem.setStreamVolumeIndex(stream, (index + 5)/10);
449    }
450
451    private int rescaleIndex(int index, int srcStream, int dstStream) {
452        return (index * mStreamStates[dstStream].getMaxIndex() + mStreamStates[srcStream].getMaxIndex() / 2) / mStreamStates[srcStream].getMaxIndex();
453    }
454
455    ///////////////////////////////////////////////////////////////////////////
456    // IPC methods
457    ///////////////////////////////////////////////////////////////////////////
458
459    /** @see AudioManager#adjustVolume(int, int) */
460    public void adjustVolume(int direction, int flags) {
461        adjustSuggestedStreamVolume(direction, AudioManager.USE_DEFAULT_STREAM_TYPE, flags);
462    }
463
464    /** @see AudioManager#adjustVolume(int, int, int) */
465    public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) {
466
467        int streamType;
468        if ((flags & AudioManager.FLAG_FORCE_STREAM) != 0) {
469            streamType = suggestedStreamType;
470        } else {
471            streamType = getActiveStreamType(suggestedStreamType);
472        }
473
474        // Don't play sound on other streams
475        if (streamType != AudioSystem.STREAM_RING && (flags & AudioManager.FLAG_PLAY_SOUND) != 0) {
476            flags &= ~AudioManager.FLAG_PLAY_SOUND;
477        }
478
479        adjustStreamVolume(streamType, direction, flags);
480    }
481
482    /** @see AudioManager#adjustStreamVolume(int, int, int) */
483    public void adjustStreamVolume(int streamType, int direction, int flags) {
484        ensureValidDirection(direction);
485        ensureValidStreamType(streamType);
486
487
488        VolumeStreamState streamState = mStreamStates[STREAM_VOLUME_ALIAS[streamType]];
489        final int oldIndex = (streamState.muteCount() != 0) ? streamState.mLastAudibleIndex : streamState.mIndex;
490        boolean adjustVolume = true;
491
492        // If either the client forces allowing ringer modes for this adjustment,
493        // or the stream type is one that is affected by ringer modes
494        if (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) ||
495             (!mVoiceCapable && streamType != AudioSystem.STREAM_VOICE_CALL &&
496               streamType != AudioSystem.STREAM_BLUETOOTH_SCO) ||
497                (mVoiceCapable && streamType == AudioSystem.STREAM_RING)) {
498            // Check if the ringer mode changes with this volume adjustment. If
499            // it does, it will handle adjusting the volume, so we won't below
500            adjustVolume = checkForRingerModeChange(oldIndex, direction);
501        }
502
503        // If stream is muted, adjust last audible index only
504        int index;
505        if (streamState.muteCount() != 0) {
506            if (adjustVolume) {
507                streamState.adjustLastAudibleIndex(direction);
508                // Post a persist volume msg
509                sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamType,
510                        SENDMSG_REPLACE, 0, 1, streamState, PERSIST_DELAY);
511            }
512            index = streamState.mLastAudibleIndex;
513        } else {
514            if (adjustVolume && streamState.adjustIndex(direction)) {
515                // Post message to set system volume (it in turn will post a message
516                // to persist). Do not change volume if stream is muted.
517                sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, STREAM_VOLUME_ALIAS[streamType], SENDMSG_NOOP, 0, 0,
518                        streamState, 0);
519            }
520            index = streamState.mIndex;
521        }
522
523        sendVolumeUpdate(streamType, oldIndex, index, flags);
524    }
525
526    /** @see AudioManager#setStreamVolume(int, int, int) */
527    public void setStreamVolume(int streamType, int index, int flags) {
528        ensureValidStreamType(streamType);
529        VolumeStreamState streamState = mStreamStates[STREAM_VOLUME_ALIAS[streamType]];
530
531        final int oldIndex = (streamState.muteCount() != 0) ? streamState.mLastAudibleIndex : streamState.mIndex;
532
533        index = rescaleIndex(index * 10, streamType, STREAM_VOLUME_ALIAS[streamType]);
534        setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, false, true);
535
536        index = (streamState.muteCount() != 0) ? streamState.mLastAudibleIndex : streamState.mIndex;
537
538        sendVolumeUpdate(streamType, oldIndex, index, flags);
539    }
540
541    // UI update and Broadcast Intent
542    private void sendVolumeUpdate(int streamType, int oldIndex, int index, int flags) {
543        if (!mVoiceCapable && (streamType == AudioSystem.STREAM_RING)) {
544            streamType = AudioSystem.STREAM_NOTIFICATION;
545        }
546
547        mVolumePanel.postVolumeChanged(streamType, flags);
548
549        oldIndex = (oldIndex + 5) / 10;
550        index = (index + 5) / 10;
551        Intent intent = new Intent(AudioManager.VOLUME_CHANGED_ACTION);
552        intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, streamType);
553        intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, index);
554        intent.putExtra(AudioManager.EXTRA_PREV_VOLUME_STREAM_VALUE, oldIndex);
555        mContext.sendBroadcast(intent);
556    }
557
558    /**
559     * Sets the stream state's index, and posts a message to set system volume.
560     * This will not call out to the UI. Assumes a valid stream type.
561     *
562     * @param streamType Type of the stream
563     * @param index Desired volume index of the stream
564     * @param force If true, set the volume even if the desired volume is same
565     * as the current volume.
566     * @param lastAudible If true, stores new index as last audible one
567     */
568    private void setStreamVolumeInt(int streamType, int index, boolean force, boolean lastAudible) {
569        VolumeStreamState streamState = mStreamStates[streamType];
570
571        // If stream is muted, set last audible index only
572        if (streamState.muteCount() != 0) {
573            // Do not allow last audible index to be 0
574            if (index != 0) {
575                streamState.setLastAudibleIndex(index);
576                // Post a persist volume msg
577                sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamType,
578                        SENDMSG_REPLACE, 0, 1, streamState, PERSIST_DELAY);
579            }
580        } else {
581            if (streamState.setIndex(index, lastAudible) || force) {
582                // Post message to set system volume (it in turn will post a message
583                // to persist).
584                sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, streamType, SENDMSG_NOOP, 0, 0,
585                        streamState, 0);
586            }
587        }
588    }
589
590    /** @see AudioManager#setStreamSolo(int, boolean) */
591    public void setStreamSolo(int streamType, boolean state, IBinder cb) {
592        for (int stream = 0; stream < mStreamStates.length; stream++) {
593            if (!isStreamAffectedByMute(stream) || stream == streamType) continue;
594            // Bring back last audible volume
595            mStreamStates[stream].mute(cb, state);
596         }
597    }
598
599    /** @see AudioManager#setStreamMute(int, boolean) */
600    public void setStreamMute(int streamType, boolean state, IBinder cb) {
601        if (isStreamAffectedByMute(streamType)) {
602            mStreamStates[streamType].mute(cb, state);
603        }
604    }
605
606    /** get stream mute state. */
607    public boolean isStreamMute(int streamType) {
608        return (mStreamStates[streamType].muteCount() != 0);
609    }
610
611    /** @see AudioManager#getStreamVolume(int) */
612    public int getStreamVolume(int streamType) {
613        ensureValidStreamType(streamType);
614        return (mStreamStates[streamType].mIndex + 5) / 10;
615    }
616
617    /** @see AudioManager#getStreamMaxVolume(int) */
618    public int getStreamMaxVolume(int streamType) {
619        ensureValidStreamType(streamType);
620        return (mStreamStates[streamType].getMaxIndex() + 5) / 10;
621    }
622
623
624    /** Get last audible volume before stream was muted. */
625    public int getLastAudibleStreamVolume(int streamType) {
626        ensureValidStreamType(streamType);
627        return (mStreamStates[streamType].mLastAudibleIndex + 5) / 10;
628    }
629
630    /** @see AudioManager#getRingerMode() */
631    public int getRingerMode() {
632        return mRingerMode;
633    }
634
635    /** @see AudioManager#setRingerMode(int) */
636    public void setRingerMode(int ringerMode) {
637        synchronized (mSettingsLock) {
638            if (ringerMode != mRingerMode) {
639                setRingerModeInt(ringerMode, true);
640                // Send sticky broadcast
641                broadcastRingerMode();
642            }
643        }
644    }
645
646    private void setRingerModeInt(int ringerMode, boolean persist) {
647        mRingerMode = ringerMode;
648
649        // Mute stream if not previously muted by ringer mode and ringer mode
650        // is not RINGER_MODE_NORMAL and stream is affected by ringer mode.
651        // Unmute stream if previously muted by ringer mode and ringer mode
652        // is RINGER_MODE_NORMAL or stream is not affected by ringer mode.
653        int numStreamTypes = AudioSystem.getNumStreamTypes();
654        for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
655            if (isStreamMutedByRingerMode(streamType)) {
656                if (!isStreamAffectedByRingerMode(streamType) ||
657                    mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
658                    mStreamStates[streamType].mute(null, false);
659                    mRingerModeMutedStreams &= ~(1 << streamType);
660                }
661            } else {
662                if (isStreamAffectedByRingerMode(streamType) &&
663                    mRingerMode != AudioManager.RINGER_MODE_NORMAL) {
664                   mStreamStates[streamType].mute(null, true);
665                   mRingerModeMutedStreams |= (1 << streamType);
666               }
667            }
668        }
669
670        // Post a persist ringer mode msg
671        if (persist) {
672            sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE, SHARED_MSG,
673                    SENDMSG_REPLACE, 0, 0, null, PERSIST_DELAY);
674        }
675    }
676
677    /** @see AudioManager#shouldVibrate(int) */
678    public boolean shouldVibrate(int vibrateType) {
679
680        switch (getVibrateSetting(vibrateType)) {
681
682            case AudioManager.VIBRATE_SETTING_ON:
683                return mRingerMode != AudioManager.RINGER_MODE_SILENT;
684
685            case AudioManager.VIBRATE_SETTING_ONLY_SILENT:
686                return mRingerMode == AudioManager.RINGER_MODE_VIBRATE;
687
688            case AudioManager.VIBRATE_SETTING_OFF:
689                // return false, even for incoming calls
690                return false;
691
692            default:
693                return false;
694        }
695    }
696
697    /** @see AudioManager#getVibrateSetting(int) */
698    public int getVibrateSetting(int vibrateType) {
699        return (mVibrateSetting >> (vibrateType * 2)) & 3;
700    }
701
702    /** @see AudioManager#setVibrateSetting(int, int) */
703    public void setVibrateSetting(int vibrateType, int vibrateSetting) {
704
705        mVibrateSetting = getValueForVibrateSetting(mVibrateSetting, vibrateType, vibrateSetting);
706
707        // Broadcast change
708        broadcastVibrateSetting(vibrateType);
709
710        // Post message to set ringer mode (it in turn will post a message
711        // to persist)
712        sendMsg(mAudioHandler, MSG_PERSIST_VIBRATE_SETTING, SHARED_MSG, SENDMSG_NOOP, 0, 0,
713                null, 0);
714    }
715
716    /**
717     * @see #setVibrateSetting(int, int)
718     */
719    public static int getValueForVibrateSetting(int existingValue, int vibrateType,
720            int vibrateSetting) {
721
722        // First clear the existing setting. Each vibrate type has two bits in
723        // the value. Note '3' is '11' in binary.
724        existingValue &= ~(3 << (vibrateType * 2));
725
726        // Set into the old value
727        existingValue |= (vibrateSetting & 3) << (vibrateType * 2);
728
729        return existingValue;
730    }
731
732    private class SetModeDeathHandler implements IBinder.DeathRecipient {
733        private IBinder mCb; // To be notified of client's death
734        private int mMode = AudioSystem.MODE_NORMAL; // Current mode set by this client
735
736        SetModeDeathHandler(IBinder cb) {
737            mCb = cb;
738        }
739
740        public void binderDied() {
741            synchronized(mSetModeDeathHandlers) {
742                Log.w(TAG, "setMode() client died");
743                int index = mSetModeDeathHandlers.indexOf(this);
744                if (index < 0) {
745                    Log.w(TAG, "unregistered setMode() client died");
746                } else {
747                    mSetModeDeathHandlers.remove(this);
748                    // If dead client was a the top of client list,
749                    // apply next mode in the stack
750                    if (index == 0) {
751                        // mSetModeDeathHandlers is never empty as the initial entry
752                        // created when AudioService starts is never removed
753                        SetModeDeathHandler hdlr = mSetModeDeathHandlers.get(0);
754                        int mode = hdlr.getMode();
755                        if (AudioService.this.mMode != mode) {
756                            if (AudioSystem.setPhoneState(mode) == AudioSystem.AUDIO_STATUS_OK) {
757                                AudioService.this.mMode = mode;
758                                if (mode != AudioSystem.MODE_NORMAL) {
759                                    synchronized(mScoClients) {
760                                        checkScoAudioState();
761                                        if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL) {
762                                            mBluetoothHeadset.stopVoiceRecognition(
763                                                    mBluetoothHeadsetDevice);
764                                            mBluetoothHeadset.stopScoUsingVirtualVoiceCall(
765                                                    mBluetoothHeadsetDevice);
766                                        } else {
767                                            clearAllScoClients(mCb, true);
768                                        }
769                                    }
770                                }
771                            }
772                        }
773                    }
774                }
775            }
776        }
777
778        public void setMode(int mode) {
779            mMode = mode;
780        }
781
782        public int getMode() {
783            return mMode;
784        }
785
786        public IBinder getBinder() {
787            return mCb;
788        }
789    }
790
791    /** @see AudioManager#setMode(int) */
792    public void setMode(int mode, IBinder cb) {
793        if (!checkAudioSettingsPermission("setMode()")) {
794            return;
795        }
796
797        if (mode < AudioSystem.MODE_CURRENT || mode >= AudioSystem.NUM_MODES) {
798            return;
799        }
800
801        synchronized (mSettingsLock) {
802            if (mode == AudioSystem.MODE_CURRENT) {
803                mode = mMode;
804            }
805            if (mode != mMode) {
806
807                // automatically handle audio focus for mode changes
808                handleFocusForCalls(mMode, mode);
809
810                if (AudioSystem.setPhoneState(mode) == AudioSystem.AUDIO_STATUS_OK) {
811                    mMode = mode;
812
813                    synchronized(mSetModeDeathHandlers) {
814                        SetModeDeathHandler hdlr = null;
815                        Iterator iter = mSetModeDeathHandlers.iterator();
816                        while (iter.hasNext()) {
817                            SetModeDeathHandler h = (SetModeDeathHandler)iter.next();
818                            if (h.getBinder() == cb) {
819                                hdlr = h;
820                                // Remove from client list so that it is re-inserted at top of list
821                                iter.remove();
822                                break;
823                            }
824                        }
825                        if (hdlr == null) {
826                            hdlr = new SetModeDeathHandler(cb);
827                            // cb is null when setMode() is called by AudioService constructor
828                            if (cb != null) {
829                                // Register for client death notification
830                                try {
831                                    cb.linkToDeath(hdlr, 0);
832                                } catch (RemoteException e) {
833                                    // Client has died!
834                                    Log.w(TAG, "setMode() could not link to "+cb+" binder death");
835                                }
836                            }
837                        }
838                        // Last client to call setMode() is always at top of client list
839                        // as required by SetModeDeathHandler.binderDied()
840                        mSetModeDeathHandlers.add(0, hdlr);
841                        hdlr.setMode(mode);
842                    }
843
844                    // when entering RINGTONE, IN_CALL or IN_COMMUNICATION mode, clear all
845                    // SCO connections not started by the application changing the mode
846                    if (mode != AudioSystem.MODE_NORMAL) {
847                        synchronized(mScoClients) {
848                            checkScoAudioState();
849                            if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL) {
850                                mBluetoothHeadset.stopVoiceRecognition(mBluetoothHeadsetDevice);
851                                mBluetoothHeadset.stopScoUsingVirtualVoiceCall(
852                                    mBluetoothHeadsetDevice);
853                            } else {
854                                clearAllScoClients(cb, true);
855                            }
856                        }
857                    }
858                }
859            }
860            int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
861            int index = mStreamStates[STREAM_VOLUME_ALIAS[streamType]].mIndex;
862            setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, true, false);
863        }
864    }
865
866    /** pre-condition: oldMode != newMode */
867    private void handleFocusForCalls(int oldMode, int newMode) {
868        // if ringing
869        if (newMode == AudioSystem.MODE_RINGTONE) {
870            // if not ringing silently
871            int ringVolume = AudioService.this.getStreamVolume(AudioManager.STREAM_RING);
872            if (ringVolume > 0) {
873                // request audio focus for the communication focus entry
874                requestAudioFocus(AudioManager.STREAM_RING,
875                        AudioManager.AUDIOFOCUS_GAIN_TRANSIENT,
876                        null, null /* both allowed to be null only for this clientId */,
877                        IN_VOICE_COMM_FOCUS_ID /*clientId*/);
878
879            }
880        }
881        // if entering call
882        else if ((newMode == AudioSystem.MODE_IN_CALL)
883                || (newMode == AudioSystem.MODE_IN_COMMUNICATION)) {
884            // request audio focus for the communication focus entry
885            // (it's ok if focus was already requested during ringing)
886            requestAudioFocus(AudioManager.STREAM_RING,
887                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT,
888                    null, null /* both allowed to be null only for this clientId */,
889                    IN_VOICE_COMM_FOCUS_ID /*clientId*/);
890        }
891        // if exiting call
892        else if (newMode == AudioSystem.MODE_NORMAL) {
893            // abandon audio focus for communication focus entry
894            abandonAudioFocus(null, IN_VOICE_COMM_FOCUS_ID);
895        }
896    }
897
898    /** @see AudioManager#getMode() */
899    public int getMode() {
900        return mMode;
901    }
902
903    /** @see AudioManager#playSoundEffect(int) */
904    public void playSoundEffect(int effectType) {
905        sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP,
906                effectType, -1, null, 0);
907    }
908
909    /** @see AudioManager#playSoundEffect(int, float) */
910    public void playSoundEffectVolume(int effectType, float volume) {
911        loadSoundEffects();
912        sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP,
913                effectType, (int) (volume * 1000), null, 0);
914    }
915
916    /**
917     * Loads samples into the soundpool.
918     * This method must be called at when sound effects are enabled
919     */
920    public boolean loadSoundEffects() {
921        int status;
922
923        synchronized (mSoundEffectsLock) {
924            if (!mBootCompleted) {
925                Log.w(TAG, "loadSoundEffects() called before boot complete");
926                return false;
927            }
928
929            if (mSoundPool != null) {
930                return true;
931            }
932            mSoundPool = new SoundPool(NUM_SOUNDPOOL_CHANNELS, AudioSystem.STREAM_SYSTEM, 0);
933            if (mSoundPool == null) {
934                Log.w(TAG, "loadSoundEffects() could not allocate sound pool");
935                return false;
936            }
937
938            try {
939                mSoundPoolCallBack = null;
940                mSoundPoolListenerThread = new SoundPoolListenerThread();
941                mSoundPoolListenerThread.start();
942                // Wait for mSoundPoolCallBack to be set by the other thread
943                mSoundEffectsLock.wait();
944            } catch (InterruptedException e) {
945                Log.w(TAG, "Interrupted while waiting sound pool listener thread.");
946            }
947
948            if (mSoundPoolCallBack == null) {
949                Log.w(TAG, "loadSoundEffects() could not create SoundPool listener or thread");
950                if (mSoundPoolLooper != null) {
951                    mSoundPoolLooper.quit();
952                    mSoundPoolLooper = null;
953                }
954                mSoundPoolListenerThread = null;
955                mSoundPool.release();
956                mSoundPool = null;
957                return false;
958            }
959            /*
960             * poolId table: The value -1 in this table indicates that corresponding
961             * file (same index in SOUND_EFFECT_FILES[] has not been loaded.
962             * Once loaded, the value in poolId is the sample ID and the same
963             * sample can be reused for another effect using the same file.
964             */
965            int[] poolId = new int[SOUND_EFFECT_FILES.length];
966            for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) {
967                poolId[fileIdx] = -1;
968            }
969            /*
970             * Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded.
971             * If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0:
972             * this indicates we have a valid sample loaded for this effect.
973             */
974
975            int lastSample = 0;
976            for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
977                // Do not load sample if this effect uses the MediaPlayer
978                if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) {
979                    continue;
980                }
981                if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) {
982                    String filePath = Environment.getRootDirectory()
983                            + SOUND_EFFECTS_PATH
984                            + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effect][0]];
985                    int sampleId = mSoundPool.load(filePath, 0);
986                    if (sampleId <= 0) {
987                        Log.w(TAG, "Soundpool could not load file: "+filePath);
988                    } else {
989                        SOUND_EFFECT_FILES_MAP[effect][1] = sampleId;
990                        poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId;
991                        lastSample = sampleId;
992                    }
993                } else {
994                    SOUND_EFFECT_FILES_MAP[effect][1] = poolId[SOUND_EFFECT_FILES_MAP[effect][0]];
995                }
996            }
997            // wait for all samples to be loaded
998            if (lastSample != 0) {
999                mSoundPoolCallBack.setLastSample(lastSample);
1000
1001                try {
1002                    mSoundEffectsLock.wait();
1003                    status = mSoundPoolCallBack.status();
1004                } catch (java.lang.InterruptedException e) {
1005                    Log.w(TAG, "Interrupted while waiting sound pool callback.");
1006                    status = -1;
1007                }
1008            } else {
1009                status = -1;
1010            }
1011
1012            if (mSoundPoolLooper != null) {
1013                mSoundPoolLooper.quit();
1014                mSoundPoolLooper = null;
1015            }
1016            mSoundPoolListenerThread = null;
1017            if (status != 0) {
1018                Log.w(TAG,
1019                        "loadSoundEffects(), Error "
1020                                + ((lastSample != 0) ? mSoundPoolCallBack.status() : -1)
1021                                + " while loading samples");
1022                for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
1023                    if (SOUND_EFFECT_FILES_MAP[effect][1] > 0) {
1024                        SOUND_EFFECT_FILES_MAP[effect][1] = -1;
1025                    }
1026                }
1027
1028                mSoundPool.release();
1029                mSoundPool = null;
1030            }
1031        }
1032        return (status == 0);
1033    }
1034
1035    /**
1036     *  Unloads samples from the sound pool.
1037     *  This method can be called to free some memory when
1038     *  sound effects are disabled.
1039     */
1040    public void unloadSoundEffects() {
1041        synchronized (mSoundEffectsLock) {
1042            if (mSoundPool == null) {
1043                return;
1044            }
1045
1046            mAudioHandler.removeMessages(MSG_LOAD_SOUND_EFFECTS);
1047            mAudioHandler.removeMessages(MSG_PLAY_SOUND_EFFECT);
1048
1049            int[] poolId = new int[SOUND_EFFECT_FILES.length];
1050            for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) {
1051                poolId[fileIdx] = 0;
1052            }
1053
1054            for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
1055                if (SOUND_EFFECT_FILES_MAP[effect][1] <= 0) {
1056                    continue;
1057                }
1058                if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == 0) {
1059                    mSoundPool.unload(SOUND_EFFECT_FILES_MAP[effect][1]);
1060                    SOUND_EFFECT_FILES_MAP[effect][1] = -1;
1061                    poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1;
1062                }
1063            }
1064            mSoundPool.release();
1065            mSoundPool = null;
1066        }
1067    }
1068
1069    class SoundPoolListenerThread extends Thread {
1070        public SoundPoolListenerThread() {
1071            super("SoundPoolListenerThread");
1072        }
1073
1074        @Override
1075        public void run() {
1076
1077            Looper.prepare();
1078            mSoundPoolLooper = Looper.myLooper();
1079
1080            synchronized (mSoundEffectsLock) {
1081                if (mSoundPool != null) {
1082                    mSoundPoolCallBack = new SoundPoolCallback();
1083                    mSoundPool.setOnLoadCompleteListener(mSoundPoolCallBack);
1084                }
1085                mSoundEffectsLock.notify();
1086            }
1087            Looper.loop();
1088        }
1089    }
1090
1091    private final class SoundPoolCallback implements
1092            android.media.SoundPool.OnLoadCompleteListener {
1093
1094        int mStatus;
1095        int mLastSample;
1096
1097        public int status() {
1098            return mStatus;
1099        }
1100
1101        public void setLastSample(int sample) {
1102            mLastSample = sample;
1103        }
1104
1105        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
1106            synchronized (mSoundEffectsLock) {
1107                if (status != 0) {
1108                    mStatus = status;
1109                }
1110                if (sampleId == mLastSample) {
1111                    mSoundEffectsLock.notify();
1112                }
1113            }
1114        }
1115    }
1116
1117    /** @see AudioManager#reloadAudioSettings() */
1118    public void reloadAudioSettings() {
1119        // restore ringer mode, ringer mode affected streams, mute affected streams and vibrate settings
1120        readPersistedSettings();
1121
1122        // restore volume settings
1123        int numStreamTypes = AudioSystem.getNumStreamTypes();
1124        for (int streamType = 0; streamType < numStreamTypes; streamType++) {
1125            VolumeStreamState streamState = mStreamStates[streamType];
1126
1127            String settingName = System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[streamType]];
1128            String lastAudibleSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE;
1129            int index = Settings.System.getInt(mContentResolver,
1130                                           settingName,
1131                                           AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1132            if (STREAM_VOLUME_ALIAS[streamType] != streamType) {
1133                index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType);
1134            } else {
1135                index *= 10;
1136            }
1137            streamState.mIndex = streamState.getValidIndex(index);
1138
1139            index = (index + 5) / 10;
1140            index = Settings.System.getInt(mContentResolver,
1141                                            lastAudibleSettingName,
1142                                            (index > 0) ? index : AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1143            if (STREAM_VOLUME_ALIAS[streamType] != streamType) {
1144                index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType);
1145            } else {
1146                index *= 10;
1147            }
1148            streamState.mLastAudibleIndex = streamState.getValidIndex(index);
1149
1150            // unmute stream that was muted but is not affect by mute anymore
1151            if (streamState.muteCount() != 0 && !isStreamAffectedByMute(streamType)) {
1152                int size = streamState.mDeathHandlers.size();
1153                for (int i = 0; i < size; i++) {
1154                    streamState.mDeathHandlers.get(i).mMuteCount = 1;
1155                    streamState.mDeathHandlers.get(i).mute(false);
1156                }
1157            }
1158            // apply stream volume
1159            if (streamState.muteCount() == 0) {
1160                setStreamVolumeIndex(streamType, streamState.mIndex);
1161            }
1162        }
1163
1164        // apply new ringer mode
1165        setRingerModeInt(getRingerMode(), false);
1166    }
1167
1168    /** @see AudioManager#setSpeakerphoneOn() */
1169    public void setSpeakerphoneOn(boolean on){
1170        if (!checkAudioSettingsPermission("setSpeakerphoneOn()")) {
1171            return;
1172        }
1173        if (on) {
1174            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_SPEAKER);
1175            mForcedUseForComm = AudioSystem.FORCE_SPEAKER;
1176        } else {
1177            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_NONE);
1178            mForcedUseForComm = AudioSystem.FORCE_NONE;
1179        }
1180    }
1181
1182    /** @see AudioManager#isSpeakerphoneOn() */
1183    public boolean isSpeakerphoneOn() {
1184        if (mForcedUseForComm == AudioSystem.FORCE_SPEAKER) {
1185            return true;
1186        } else {
1187            return false;
1188        }
1189    }
1190
1191    /** @see AudioManager#setBluetoothScoOn() */
1192    public void setBluetoothScoOn(boolean on){
1193        if (!checkAudioSettingsPermission("setBluetoothScoOn()")) {
1194            return;
1195        }
1196        if (on) {
1197            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_BT_SCO);
1198            AudioSystem.setForceUse(AudioSystem.FOR_RECORD, AudioSystem.FORCE_BT_SCO);
1199            mForcedUseForComm = AudioSystem.FORCE_BT_SCO;
1200        } else {
1201            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_NONE);
1202            AudioSystem.setForceUse(AudioSystem.FOR_RECORD, AudioSystem.FORCE_NONE);
1203            mForcedUseForComm = AudioSystem.FORCE_NONE;
1204        }
1205    }
1206
1207    /** @see AudioManager#isBluetoothScoOn() */
1208    public boolean isBluetoothScoOn() {
1209        if (mForcedUseForComm == AudioSystem.FORCE_BT_SCO) {
1210            return true;
1211        } else {
1212            return false;
1213        }
1214    }
1215
1216    /** @see AudioManager#startBluetoothSco() */
1217    public void startBluetoothSco(IBinder cb){
1218        if (!checkAudioSettingsPermission("startBluetoothSco()")) {
1219            return;
1220        }
1221        ScoClient client = getScoClient(cb);
1222        client.incCount();
1223    }
1224
1225    /** @see AudioManager#stopBluetoothSco() */
1226    public void stopBluetoothSco(IBinder cb){
1227        if (!checkAudioSettingsPermission("stopBluetoothSco()")) {
1228            return;
1229        }
1230        ScoClient client = getScoClient(cb);
1231        client.decCount();
1232    }
1233
1234    private class ScoClient implements IBinder.DeathRecipient {
1235        private IBinder mCb; // To be notified of client's death
1236        private int mStartcount; // number of SCO connections started by this client
1237
1238        ScoClient(IBinder cb) {
1239            mCb = cb;
1240            mStartcount = 0;
1241        }
1242
1243        public void binderDied() {
1244            synchronized(mScoClients) {
1245                Log.w(TAG, "SCO client died");
1246                int index = mScoClients.indexOf(this);
1247                if (index < 0) {
1248                    Log.w(TAG, "unregistered SCO client died");
1249                } else {
1250                    clearCount(true);
1251                    mScoClients.remove(this);
1252                }
1253            }
1254        }
1255
1256        public void incCount() {
1257            synchronized(mScoClients) {
1258                requestScoState(BluetoothHeadset.STATE_AUDIO_CONNECTED);
1259                if (mStartcount == 0) {
1260                    try {
1261                        mCb.linkToDeath(this, 0);
1262                    } catch (RemoteException e) {
1263                        // client has already died!
1264                        Log.w(TAG, "ScoClient  incCount() could not link to "+mCb+" binder death");
1265                    }
1266                }
1267                mStartcount++;
1268            }
1269        }
1270
1271        public void decCount() {
1272            synchronized(mScoClients) {
1273                if (mStartcount == 0) {
1274                    Log.w(TAG, "ScoClient.decCount() already 0");
1275                } else {
1276                    mStartcount--;
1277                    if (mStartcount == 0) {
1278                        try {
1279                            mCb.unlinkToDeath(this, 0);
1280                        } catch (NoSuchElementException e) {
1281                            Log.w(TAG, "decCount() going to 0 but not registered to binder");
1282                        }
1283                    }
1284                    requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
1285                }
1286            }
1287        }
1288
1289        public void clearCount(boolean stopSco) {
1290            synchronized(mScoClients) {
1291                if (mStartcount != 0) {
1292                    try {
1293                        mCb.unlinkToDeath(this, 0);
1294                    } catch (NoSuchElementException e) {
1295                        Log.w(TAG, "clearCount() mStartcount: "+mStartcount+" != 0 but not registered to binder");
1296                    }
1297                }
1298                mStartcount = 0;
1299                if (stopSco) {
1300                    requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
1301                }
1302            }
1303        }
1304
1305        public int getCount() {
1306            return mStartcount;
1307        }
1308
1309        public IBinder getBinder() {
1310            return mCb;
1311        }
1312
1313        public int totalCount() {
1314            synchronized(mScoClients) {
1315                int count = 0;
1316                int size = mScoClients.size();
1317                for (int i = 0; i < size; i++) {
1318                    count += mScoClients.get(i).getCount();
1319                }
1320                return count;
1321            }
1322        }
1323
1324        private void requestScoState(int state) {
1325            if (mBluetoothHeadset == null) {
1326                return;
1327            }
1328
1329            checkScoAudioState();
1330
1331            if (totalCount() == 0 &&
1332                mBluetoothHeadsetDevice != null) {
1333                // Accept SCO audio activation only in NORMAL audio mode or if the mode is
1334                // currently controlled by the same client.
1335                if ((AudioService.this.mMode == AudioSystem.MODE_NORMAL ||
1336                        mSetModeDeathHandlers.get(0).getBinder() == mCb) &&
1337                        state == BluetoothHeadset.STATE_AUDIO_CONNECTED &&
1338                        mScoAudioState == SCO_STATE_INACTIVE) {
1339                    mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
1340                    mBluetoothHeadset.startScoUsingVirtualVoiceCall(mBluetoothHeadsetDevice);
1341                } else if (state == BluetoothHeadset.STATE_AUDIO_DISCONNECTED &&
1342                        mScoAudioState == SCO_STATE_ACTIVE_INTERNAL){
1343                    mBluetoothHeadset.stopScoUsingVirtualVoiceCall(mBluetoothHeadsetDevice);
1344                }
1345            }
1346        }
1347    }
1348
1349    private void checkScoAudioState() {
1350        if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null &&
1351                mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
1352                mBluetoothHeadset.getAudioState(mBluetoothHeadsetDevice)
1353                != BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
1354            mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
1355        }
1356    }
1357
1358    public ScoClient getScoClient(IBinder cb) {
1359        synchronized(mScoClients) {
1360            ScoClient client;
1361            int size = mScoClients.size();
1362            for (int i = 0; i < size; i++) {
1363                client = mScoClients.get(i);
1364                if (client.getBinder() == cb)
1365                    return client;
1366            }
1367            client = new ScoClient(cb);
1368            mScoClients.add(client);
1369            return client;
1370        }
1371    }
1372
1373    public void clearAllScoClients(IBinder exceptBinder, boolean stopSco) {
1374        synchronized(mScoClients) {
1375            int size = mScoClients.size();
1376            for (int i = 0; i < size; i++) {
1377                if (mScoClients.get(i).getBinder() != exceptBinder)
1378                    mScoClients.get(i).clearCount(stopSco);
1379            }
1380        }
1381    }
1382
1383    private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
1384        new BluetoothProfile.ServiceListener() {
1385        public void onServiceConnected(int profile, BluetoothProfile proxy) {
1386            synchronized (mScoClients) {
1387                mBluetoothHeadset = (BluetoothHeadset) proxy;
1388                List<BluetoothDevice> deviceList = mBluetoothHeadset.getConnectedDevices();
1389                if (deviceList.size() > 0) {
1390                    mBluetoothHeadsetDevice = deviceList.get(0);
1391                } else {
1392                    mBluetoothHeadsetDevice = null;
1393                }
1394            }
1395        }
1396        public void onServiceDisconnected(int profile) {
1397            synchronized (mScoClients) {
1398                if (mBluetoothHeadset != null) {
1399                    List<BluetoothDevice> devices = mBluetoothHeadset.getConnectedDevices();
1400                    if (devices.size() == 0) {
1401                        mBluetoothHeadsetDevice = null;
1402                        clearAllScoClients(null, false);
1403                        mScoAudioState = SCO_STATE_INACTIVE;
1404                    }
1405                    mBluetoothHeadset = null;
1406                }
1407            }
1408        }
1409    };
1410
1411    ///////////////////////////////////////////////////////////////////////////
1412    // Internal methods
1413    ///////////////////////////////////////////////////////////////////////////
1414
1415    /**
1416     * Checks if the adjustment should change ringer mode instead of just
1417     * adjusting volume. If so, this will set the proper ringer mode and volume
1418     * indices on the stream states.
1419     */
1420    private boolean checkForRingerModeChange(int oldIndex, int direction) {
1421        boolean adjustVolumeIndex = true;
1422        int newRingerMode = mRingerMode;
1423
1424        if (mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
1425            // audible mode, at the bottom of the scale
1426            if ((direction == AudioManager.ADJUST_LOWER &&
1427                 mPrevVolDirection != AudioManager.ADJUST_LOWER) &&
1428                ((oldIndex + 5) / 10 == 0)) {
1429                // "silent mode", but which one?
1430                newRingerMode = System.getInt(mContentResolver, System.VIBRATE_IN_SILENT, 1) == 1
1431                    ? AudioManager.RINGER_MODE_VIBRATE
1432                    : AudioManager.RINGER_MODE_SILENT;
1433            }
1434        } else {
1435            if (direction == AudioManager.ADJUST_RAISE) {
1436                // exiting silent mode
1437                newRingerMode = AudioManager.RINGER_MODE_NORMAL;
1438            } else {
1439                // prevent last audible index to reach 0
1440                adjustVolumeIndex = false;
1441            }
1442        }
1443
1444        if (newRingerMode != mRingerMode) {
1445            setRingerMode(newRingerMode);
1446
1447            /*
1448             * If we are changing ringer modes, do not increment/decrement the
1449             * volume index. Instead, the handler for the message above will
1450             * take care of changing the index.
1451             */
1452            adjustVolumeIndex = false;
1453        }
1454
1455        mPrevVolDirection = direction;
1456
1457        return adjustVolumeIndex;
1458    }
1459
1460    public boolean isStreamAffectedByRingerMode(int streamType) {
1461        return (mRingerModeAffectedStreams & (1 << streamType)) != 0;
1462    }
1463
1464    private boolean isStreamMutedByRingerMode(int streamType) {
1465        return (mRingerModeMutedStreams & (1 << streamType)) != 0;
1466    }
1467
1468    public boolean isStreamAffectedByMute(int streamType) {
1469        return (mMuteAffectedStreams & (1 << streamType)) != 0;
1470    }
1471
1472    private void ensureValidDirection(int direction) {
1473        if (direction < AudioManager.ADJUST_LOWER || direction > AudioManager.ADJUST_RAISE) {
1474            throw new IllegalArgumentException("Bad direction " + direction);
1475        }
1476    }
1477
1478    private void ensureValidStreamType(int streamType) {
1479        if (streamType < 0 || streamType >= mStreamStates.length) {
1480            throw new IllegalArgumentException("Bad stream type " + streamType);
1481        }
1482    }
1483
1484    private int getActiveStreamType(int suggestedStreamType) {
1485
1486        if (mVoiceCapable) {
1487            boolean isOffhook = false;
1488            try {
1489                ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
1490                if (phone != null) isOffhook = phone.isOffhook();
1491            } catch (RemoteException e) {
1492                Log.w(TAG, "Couldn't connect to phone service", e);
1493            }
1494
1495            if (isOffhook || getMode() == AudioManager.MODE_IN_COMMUNICATION) {
1496                if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION)
1497                        == AudioSystem.FORCE_BT_SCO) {
1498                    // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO...");
1499                    return AudioSystem.STREAM_BLUETOOTH_SCO;
1500                } else {
1501                    // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL...");
1502                    return AudioSystem.STREAM_VOICE_CALL;
1503                }
1504            } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0)) {
1505                // Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC...");
1506                return AudioSystem.STREAM_MUSIC;
1507            } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
1508                // Log.v(TAG, "getActiveStreamType: Forcing STREAM_RING..."
1509                //        + " b/c USE_DEFAULT_STREAM_TYPE...");
1510                return AudioSystem.STREAM_RING;
1511            } else {
1512                // Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType);
1513                return suggestedStreamType;
1514            }
1515        } else {
1516            if (getMode() == AudioManager.MODE_IN_COMMUNICATION) {
1517                if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION)
1518                        == AudioSystem.FORCE_BT_SCO) {
1519                    // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO...");
1520                    return AudioSystem.STREAM_BLUETOOTH_SCO;
1521                } else {
1522                    // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL...");
1523                    return AudioSystem.STREAM_VOICE_CALL;
1524                }
1525            } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_NOTIFICATION,
1526                            NOTIFICATION_VOLUME_DELAY_MS) ||
1527                       AudioSystem.isStreamActive(AudioSystem.STREAM_RING,
1528                            NOTIFICATION_VOLUME_DELAY_MS)) {
1529                // Log.v(TAG, "getActiveStreamType: Forcing STREAM_NOTIFICATION...");
1530                return AudioSystem.STREAM_NOTIFICATION;
1531            } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0) ||
1532                       (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE)) {
1533                // Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC "
1534                //        + " b/c USE_DEFAULT_STREAM_TYPE...");
1535                return AudioSystem.STREAM_MUSIC;
1536            } else {
1537                // Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType);
1538                return suggestedStreamType;
1539            }
1540        }
1541    }
1542
1543    private void broadcastRingerMode() {
1544        // Send sticky broadcast
1545        Intent broadcast = new Intent(AudioManager.RINGER_MODE_CHANGED_ACTION);
1546        broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, mRingerMode);
1547        broadcast.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
1548                | Intent.FLAG_RECEIVER_REPLACE_PENDING);
1549        long origCallerIdentityToken = Binder.clearCallingIdentity();
1550        mContext.sendStickyBroadcast(broadcast);
1551        Binder.restoreCallingIdentity(origCallerIdentityToken);
1552    }
1553
1554    private void broadcastVibrateSetting(int vibrateType) {
1555        // Send broadcast
1556        if (ActivityManagerNative.isSystemReady()) {
1557            Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION);
1558            broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType);
1559            broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType));
1560            mContext.sendBroadcast(broadcast);
1561        }
1562    }
1563
1564    // Message helper methods
1565    private static int getMsg(int baseMsg, int streamType) {
1566        return (baseMsg & 0xffff) | streamType << 16;
1567    }
1568
1569    private static int getMsgBase(int msg) {
1570        return msg & 0xffff;
1571    }
1572
1573    private static void sendMsg(Handler handler, int baseMsg, int streamType,
1574            int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) {
1575        int msg = (streamType == SHARED_MSG) ? baseMsg : getMsg(baseMsg, streamType);
1576
1577        if (existingMsgPolicy == SENDMSG_REPLACE) {
1578            handler.removeMessages(msg);
1579        } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) {
1580            return;
1581        }
1582
1583        handler
1584                .sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delay);
1585    }
1586
1587    boolean checkAudioSettingsPermission(String method) {
1588        if (mContext.checkCallingOrSelfPermission("android.permission.MODIFY_AUDIO_SETTINGS")
1589                == PackageManager.PERMISSION_GRANTED) {
1590            return true;
1591        }
1592        String msg = "Audio Settings Permission Denial: " + method + " from pid="
1593                + Binder.getCallingPid()
1594                + ", uid=" + Binder.getCallingUid();
1595        Log.w(TAG, msg);
1596        return false;
1597    }
1598
1599
1600    ///////////////////////////////////////////////////////////////////////////
1601    // Inner classes
1602    ///////////////////////////////////////////////////////////////////////////
1603
1604    public class VolumeStreamState {
1605        private final int mStreamType;
1606
1607        private String mVolumeIndexSettingName;
1608        private String mLastAudibleVolumeIndexSettingName;
1609        private int mIndexMax;
1610        private int mIndex;
1611        private int mLastAudibleIndex;
1612        private ArrayList<VolumeDeathHandler> mDeathHandlers; //handles mute/solo requests client death
1613
1614        private VolumeStreamState(String settingName, int streamType) {
1615
1616            setVolumeIndexSettingName(settingName);
1617
1618            mStreamType = streamType;
1619
1620            final ContentResolver cr = mContentResolver;
1621            mIndexMax = MAX_STREAM_VOLUME[streamType];
1622            mIndex = Settings.System.getInt(cr,
1623                                            mVolumeIndexSettingName,
1624                                            AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1625            mLastAudibleIndex = Settings.System.getInt(cr,
1626                                                       mLastAudibleVolumeIndexSettingName,
1627                                                       (mIndex > 0) ? mIndex : AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1628            AudioSystem.initStreamVolume(streamType, 0, mIndexMax);
1629            mIndexMax *= 10;
1630            mIndex = getValidIndex(10 * mIndex);
1631            mLastAudibleIndex = getValidIndex(10 * mLastAudibleIndex);
1632            setStreamVolumeIndex(streamType, mIndex);
1633            mDeathHandlers = new ArrayList<VolumeDeathHandler>();
1634        }
1635
1636        public void setVolumeIndexSettingName(String settingName) {
1637            mVolumeIndexSettingName = settingName;
1638            mLastAudibleVolumeIndexSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE;
1639        }
1640
1641        public boolean adjustIndex(int deltaIndex) {
1642            return setIndex(mIndex + deltaIndex * 10, true);
1643        }
1644
1645        public boolean setIndex(int index, boolean lastAudible) {
1646            int oldIndex = mIndex;
1647            mIndex = getValidIndex(index);
1648
1649            if (oldIndex != mIndex) {
1650                if (lastAudible) {
1651                    mLastAudibleIndex = mIndex;
1652                }
1653                // Apply change to all streams using this one as alias
1654                int numStreamTypes = AudioSystem.getNumStreamTypes();
1655                for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
1656                    if (streamType != mStreamType && STREAM_VOLUME_ALIAS[streamType] == mStreamType) {
1657                        mStreamStates[streamType].setIndex(rescaleIndex(mIndex, mStreamType, streamType), lastAudible);
1658                    }
1659                }
1660                return true;
1661            } else {
1662                return false;
1663            }
1664        }
1665
1666        public void setLastAudibleIndex(int index) {
1667            mLastAudibleIndex = getValidIndex(index);
1668        }
1669
1670        public void adjustLastAudibleIndex(int deltaIndex) {
1671            setLastAudibleIndex(mLastAudibleIndex + deltaIndex * 10);
1672        }
1673
1674        public int getMaxIndex() {
1675            return mIndexMax;
1676        }
1677
1678        public void mute(IBinder cb, boolean state) {
1679            VolumeDeathHandler handler = getDeathHandler(cb, state);
1680            if (handler == null) {
1681                Log.e(TAG, "Could not get client death handler for stream: "+mStreamType);
1682                return;
1683            }
1684            handler.mute(state);
1685        }
1686
1687        private int getValidIndex(int index) {
1688            if (index < 0) {
1689                return 0;
1690            } else if (index > mIndexMax) {
1691                return mIndexMax;
1692            }
1693
1694            return index;
1695        }
1696
1697        private class VolumeDeathHandler implements IBinder.DeathRecipient {
1698            private IBinder mICallback; // To be notified of client's death
1699            private int mMuteCount; // Number of active mutes for this client
1700
1701            VolumeDeathHandler(IBinder cb) {
1702                mICallback = cb;
1703            }
1704
1705            public void mute(boolean state) {
1706                synchronized(mDeathHandlers) {
1707                    if (state) {
1708                        if (mMuteCount == 0) {
1709                            // Register for client death notification
1710                            try {
1711                                // mICallback can be 0 if muted by AudioService
1712                                if (mICallback != null) {
1713                                    mICallback.linkToDeath(this, 0);
1714                                }
1715                                mDeathHandlers.add(this);
1716                                // If the stream is not yet muted by any client, set lvel to 0
1717                                if (muteCount() == 0) {
1718                                    setIndex(0, false);
1719                                    sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0,
1720                                            VolumeStreamState.this, 0);
1721                                }
1722                            } catch (RemoteException e) {
1723                                // Client has died!
1724                                binderDied();
1725                                mDeathHandlers.notify();
1726                                return;
1727                            }
1728                        } else {
1729                            Log.w(TAG, "stream: "+mStreamType+" was already muted by this client");
1730                        }
1731                        mMuteCount++;
1732                    } else {
1733                        if (mMuteCount == 0) {
1734                            Log.e(TAG, "unexpected unmute for stream: "+mStreamType);
1735                        } else {
1736                            mMuteCount--;
1737                            if (mMuteCount == 0) {
1738                                // Unregistr from client death notification
1739                                mDeathHandlers.remove(this);
1740                                // mICallback can be 0 if muted by AudioService
1741                                if (mICallback != null) {
1742                                    mICallback.unlinkToDeath(this, 0);
1743                                }
1744                                if (muteCount() == 0) {
1745                                    // If the stream is not muted any more, restore it's volume if
1746                                    // ringer mode allows it
1747                                    if (!isStreamAffectedByRingerMode(mStreamType) || mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
1748                                        setIndex(mLastAudibleIndex, false);
1749                                        sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0,
1750                                                VolumeStreamState.this, 0);
1751                                    }
1752                                }
1753                            }
1754                        }
1755                    }
1756                    mDeathHandlers.notify();
1757                }
1758            }
1759
1760            public void binderDied() {
1761                Log.w(TAG, "Volume service client died for stream: "+mStreamType);
1762                if (mMuteCount != 0) {
1763                    // Reset all active mute requests from this client.
1764                    mMuteCount = 1;
1765                    mute(false);
1766                }
1767            }
1768        }
1769
1770        private int muteCount() {
1771            int count = 0;
1772            int size = mDeathHandlers.size();
1773            for (int i = 0; i < size; i++) {
1774                count += mDeathHandlers.get(i).mMuteCount;
1775            }
1776            return count;
1777        }
1778
1779        private VolumeDeathHandler getDeathHandler(IBinder cb, boolean state) {
1780            synchronized(mDeathHandlers) {
1781                VolumeDeathHandler handler;
1782                int size = mDeathHandlers.size();
1783                for (int i = 0; i < size; i++) {
1784                    handler = mDeathHandlers.get(i);
1785                    if (cb == handler.mICallback) {
1786                        return handler;
1787                    }
1788                }
1789                // If this is the first mute request for this client, create a new
1790                // client death handler. Otherwise, it is an out of sequence unmute request.
1791                if (state) {
1792                    handler = new VolumeDeathHandler(cb);
1793                } else {
1794                    Log.w(TAG, "stream was not muted by this client");
1795                    handler = null;
1796                }
1797                return handler;
1798            }
1799        }
1800    }
1801
1802    /** Thread that handles native AudioSystem control. */
1803    private class AudioSystemThread extends Thread {
1804        AudioSystemThread() {
1805            super("AudioService");
1806        }
1807
1808        @Override
1809        public void run() {
1810            // Set this thread up so the handler will work on it
1811            Looper.prepare();
1812
1813            synchronized(AudioService.this) {
1814                mAudioHandler = new AudioHandler();
1815
1816                // Notify that the handler has been created
1817                AudioService.this.notify();
1818            }
1819
1820            // Listen for volume change requests that are set by VolumePanel
1821            Looper.loop();
1822        }
1823    }
1824
1825    /** Handles internal volume messages in separate volume thread. */
1826    private class AudioHandler extends Handler {
1827
1828        private void setSystemVolume(VolumeStreamState streamState) {
1829
1830            // Adjust volume
1831            setStreamVolumeIndex(streamState.mStreamType, streamState.mIndex);
1832
1833            // Apply change to all streams using this one as alias
1834            int numStreamTypes = AudioSystem.getNumStreamTypes();
1835            for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
1836                if (streamType != streamState.mStreamType &&
1837                    STREAM_VOLUME_ALIAS[streamType] == streamState.mStreamType) {
1838                    setStreamVolumeIndex(streamType, mStreamStates[streamType].mIndex);
1839                }
1840            }
1841
1842            // Post a persist volume msg
1843            sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamState.mStreamType,
1844                    SENDMSG_REPLACE, 1, 1, streamState, PERSIST_DELAY);
1845        }
1846
1847        private void persistVolume(VolumeStreamState streamState, boolean current, boolean lastAudible) {
1848            if (current) {
1849                System.putInt(mContentResolver, streamState.mVolumeIndexSettingName,
1850                              (streamState.mIndex + 5)/ 10);
1851            }
1852            if (lastAudible) {
1853                System.putInt(mContentResolver, streamState.mLastAudibleVolumeIndexSettingName,
1854                    (streamState.mLastAudibleIndex + 5) / 10);
1855            }
1856        }
1857
1858        private void persistRingerMode() {
1859            System.putInt(mContentResolver, System.MODE_RINGER, mRingerMode);
1860        }
1861
1862        private void persistVibrateSetting() {
1863            System.putInt(mContentResolver, System.VIBRATE_ON, mVibrateSetting);
1864        }
1865
1866        private void playSoundEffect(int effectType, int volume) {
1867            synchronized (mSoundEffectsLock) {
1868                if (mSoundPool == null) {
1869                    return;
1870                }
1871                float volFloat;
1872                // use default if volume is not specified by caller
1873                if (volume < 0) {
1874                    volFloat = (float)Math.pow(10, SOUND_EFFECT_VOLUME_DB/20);
1875                } else {
1876                    volFloat = (float) volume / 1000.0f;
1877                }
1878
1879                if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) {
1880                    mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1], volFloat, volFloat, 0, 0, 1.0f);
1881                } else {
1882                    MediaPlayer mediaPlayer = new MediaPlayer();
1883                    if (mediaPlayer != null) {
1884                        try {
1885                            String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effectType][0]];
1886                            mediaPlayer.setDataSource(filePath);
1887                            mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM);
1888                            mediaPlayer.prepare();
1889                            mediaPlayer.setVolume(volFloat, volFloat);
1890                            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
1891                                public void onCompletion(MediaPlayer mp) {
1892                                    cleanupPlayer(mp);
1893                                }
1894                            });
1895                            mediaPlayer.setOnErrorListener(new OnErrorListener() {
1896                                public boolean onError(MediaPlayer mp, int what, int extra) {
1897                                    cleanupPlayer(mp);
1898                                    return true;
1899                                }
1900                            });
1901                            mediaPlayer.start();
1902                        } catch (IOException ex) {
1903                            Log.w(TAG, "MediaPlayer IOException: "+ex);
1904                        } catch (IllegalArgumentException ex) {
1905                            Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex);
1906                        } catch (IllegalStateException ex) {
1907                            Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
1908                        }
1909                    }
1910                }
1911            }
1912        }
1913
1914        private void cleanupPlayer(MediaPlayer mp) {
1915            if (mp != null) {
1916                try {
1917                    mp.stop();
1918                    mp.release();
1919                } catch (IllegalStateException ex) {
1920                    Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
1921                }
1922            }
1923        }
1924
1925        @Override
1926        public void handleMessage(Message msg) {
1927            int baseMsgWhat = getMsgBase(msg.what);
1928
1929            switch (baseMsgWhat) {
1930
1931                case MSG_SET_SYSTEM_VOLUME:
1932                    setSystemVolume((VolumeStreamState) msg.obj);
1933                    break;
1934
1935                case MSG_PERSIST_VOLUME:
1936                    persistVolume((VolumeStreamState) msg.obj, (msg.arg1 != 0), (msg.arg2 != 0));
1937                    break;
1938
1939                case MSG_PERSIST_RINGER_MODE:
1940                    persistRingerMode();
1941                    break;
1942
1943                case MSG_PERSIST_VIBRATE_SETTING:
1944                    persistVibrateSetting();
1945                    break;
1946
1947                case MSG_MEDIA_SERVER_DIED:
1948                    if (!mMediaServerOk) {
1949                        Log.e(TAG, "Media server died.");
1950                        // Force creation of new IAudioFlinger interface so that we are notified
1951                        // when new media_server process is back to life.
1952                        AudioSystem.setErrorCallback(mAudioSystemCallback);
1953                        sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
1954                                null, 500);
1955                    }
1956                    break;
1957
1958                case MSG_MEDIA_SERVER_STARTED:
1959                    Log.e(TAG, "Media server started.");
1960                    // indicate to audio HAL that we start the reconfiguration phase after a media
1961                    // server crash
1962                    // Note that MSG_MEDIA_SERVER_STARTED message is only received when the media server
1963                    // process restarts after a crash, not the first time it is started.
1964                    AudioSystem.setParameters("restarting=true");
1965
1966                    // Restore device connection states
1967                    Set set = mConnectedDevices.entrySet();
1968                    Iterator i = set.iterator();
1969                    while(i.hasNext()){
1970                        Map.Entry device = (Map.Entry)i.next();
1971                        AudioSystem.setDeviceConnectionState(((Integer)device.getKey()).intValue(),
1972                                                             AudioSystem.DEVICE_STATE_AVAILABLE,
1973                                                             (String)device.getValue());
1974                    }
1975
1976                    // Restore call state
1977                    AudioSystem.setPhoneState(mMode);
1978
1979                    // Restore forced usage for communcations and record
1980                    AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, mForcedUseForComm);
1981                    AudioSystem.setForceUse(AudioSystem.FOR_RECORD, mForcedUseForComm);
1982
1983                    // Restore stream volumes
1984                    int numStreamTypes = AudioSystem.getNumStreamTypes();
1985                    for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
1986                        int index;
1987                        VolumeStreamState streamState = mStreamStates[streamType];
1988                        AudioSystem.initStreamVolume(streamType, 0, (streamState.mIndexMax + 5) / 10);
1989                        if (streamState.muteCount() == 0) {
1990                            index = streamState.mIndex;
1991                        } else {
1992                            index = 0;
1993                        }
1994                        setStreamVolumeIndex(streamType, index);
1995                    }
1996
1997                    // Restore ringer mode
1998                    setRingerModeInt(getRingerMode(), false);
1999
2000                    // indicate the end of reconfiguration phase to audio HAL
2001                    AudioSystem.setParameters("restarting=false");
2002                    break;
2003
2004                case MSG_LOAD_SOUND_EFFECTS:
2005                    loadSoundEffects();
2006                    break;
2007
2008                case MSG_PLAY_SOUND_EFFECT:
2009                    playSoundEffect(msg.arg1, msg.arg2);
2010                    break;
2011
2012                case MSG_BTA2DP_DOCK_TIMEOUT:
2013                    // msg.obj  == address of BTA2DP device
2014                    makeA2dpDeviceUnavailableNow( (String) msg.obj );
2015                    break;
2016            }
2017        }
2018    }
2019
2020    private class SettingsObserver extends ContentObserver {
2021
2022        SettingsObserver() {
2023            super(new Handler());
2024            mContentResolver.registerContentObserver(Settings.System.getUriFor(
2025                Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this);
2026            mContentResolver.registerContentObserver(Settings.System.getUriFor(
2027                    Settings.System.NOTIFICATIONS_USE_RING_VOLUME), false, this);
2028        }
2029
2030        @Override
2031        public void onChange(boolean selfChange) {
2032            super.onChange(selfChange);
2033            synchronized (mSettingsLock) {
2034                int ringerModeAffectedStreams = Settings.System.getInt(mContentResolver,
2035                        Settings.System.MODE_RINGER_STREAMS_AFFECTED,
2036                        0);
2037                if (!mVoiceCapable) {
2038                    ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_MUSIC);
2039                }
2040
2041                if (ringerModeAffectedStreams != mRingerModeAffectedStreams) {
2042                    /*
2043                     * Ensure all stream types that should be affected by ringer mode
2044                     * are in the proper state.
2045                     */
2046                    mRingerModeAffectedStreams = ringerModeAffectedStreams;
2047                    setRingerModeInt(getRingerMode(), false);
2048                }
2049
2050                int notificationsUseRingVolume = Settings.System.getInt(mContentResolver,
2051                        Settings.System.NOTIFICATIONS_USE_RING_VOLUME,
2052                        1);
2053                if (mVoiceCapable) {
2054                    if (notificationsUseRingVolume != mNotificationsUseRingVolume) {
2055                        mNotificationsUseRingVolume = notificationsUseRingVolume;
2056                        if (mNotificationsUseRingVolume == 1) {
2057                            STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING;
2058                            mStreamStates[AudioSystem.STREAM_NOTIFICATION].setVolumeIndexSettingName(
2059                                    System.VOLUME_SETTINGS[AudioSystem.STREAM_RING]);
2060                        } else {
2061                            STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_NOTIFICATION;
2062                            mStreamStates[AudioSystem.STREAM_NOTIFICATION].setVolumeIndexSettingName(
2063                                    System.VOLUME_SETTINGS[AudioSystem.STREAM_NOTIFICATION]);
2064                            // Persist notification volume volume as it was not persisted while aliased to ring volume
2065                            //  and persist with no delay as there might be registered observers of the persisted
2066                            //  notification volume.
2067                            sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, AudioSystem.STREAM_NOTIFICATION,
2068                                    SENDMSG_REPLACE, 1, 1, mStreamStates[AudioSystem.STREAM_NOTIFICATION], 0);
2069                        }
2070                    }
2071                }
2072            }
2073        }
2074    }
2075
2076    private void makeA2dpDeviceAvailable(String address) {
2077        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
2078                AudioSystem.DEVICE_STATE_AVAILABLE,
2079                address);
2080        // Reset A2DP suspend state each time a new sink is connected
2081        AudioSystem.setParameters("A2dpSuspended=false");
2082        mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP),
2083                address);
2084    }
2085
2086    private void makeA2dpDeviceUnavailableNow(String address) {
2087        Intent noisyIntent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
2088        mContext.sendBroadcast(noisyIntent);
2089        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
2090                AudioSystem.DEVICE_STATE_UNAVAILABLE,
2091                address);
2092        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
2093    }
2094
2095    private void makeA2dpDeviceUnavailableLater(String address) {
2096        // prevent any activity on the A2DP audio output to avoid unwanted
2097        // reconnection of the sink.
2098        AudioSystem.setParameters("A2dpSuspended=true");
2099        // the device will be made unavailable later, so consider it disconnected right away
2100        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
2101        // send the delayed message to make the device unavailable later
2102        Message msg = mAudioHandler.obtainMessage(MSG_BTA2DP_DOCK_TIMEOUT, address);
2103        mAudioHandler.sendMessageDelayed(msg, BTA2DP_DOCK_TIMEOUT_MILLIS);
2104
2105    }
2106
2107    private void cancelA2dpDeviceTimeout() {
2108        mAudioHandler.removeMessages(MSG_BTA2DP_DOCK_TIMEOUT);
2109    }
2110
2111    private boolean hasScheduledA2dpDockTimeout() {
2112        return mAudioHandler.hasMessages(MSG_BTA2DP_DOCK_TIMEOUT);
2113    }
2114
2115    /* cache of the address of the last dock the device was connected to */
2116    private String mDockAddress;
2117
2118    /**
2119     * Receiver for misc intent broadcasts the Phone app cares about.
2120     */
2121    private class AudioServiceBroadcastReceiver extends BroadcastReceiver {
2122        @Override
2123        public void onReceive(Context context, Intent intent) {
2124            String action = intent.getAction();
2125
2126            if (action.equals(Intent.ACTION_DOCK_EVENT)) {
2127                int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
2128                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
2129                int config;
2130                switch (dockState) {
2131                    case Intent.EXTRA_DOCK_STATE_DESK:
2132                        config = AudioSystem.FORCE_BT_DESK_DOCK;
2133                        break;
2134                    case Intent.EXTRA_DOCK_STATE_CAR:
2135                        config = AudioSystem.FORCE_BT_CAR_DOCK;
2136                        break;
2137                    case Intent.EXTRA_DOCK_STATE_LE_DESK:
2138                        config = AudioSystem.FORCE_ANALOG_DOCK;
2139                        break;
2140                    case Intent.EXTRA_DOCK_STATE_HE_DESK:
2141                        config = AudioSystem.FORCE_DIGITAL_DOCK;
2142                        break;
2143                    case Intent.EXTRA_DOCK_STATE_UNDOCKED:
2144                    default:
2145                        config = AudioSystem.FORCE_NONE;
2146                }
2147                AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
2148            } else if (action.equals(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED)) {
2149                int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
2150                                               BluetoothProfile.STATE_DISCONNECTED);
2151                BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
2152                String address = btDevice.getAddress();
2153                boolean isConnected =
2154                    (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP) &&
2155                     mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP).equals(address));
2156
2157                if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
2158                    if (btDevice.isBluetoothDock()) {
2159                        if (state == BluetoothProfile.STATE_DISCONNECTED) {
2160                            // introduction of a delay for transient disconnections of docks when
2161                            // power is rapidly turned off/on, this message will be canceled if
2162                            // we reconnect the dock under a preset delay
2163                            makeA2dpDeviceUnavailableLater(address);
2164                            // the next time isConnected is evaluated, it will be false for the dock
2165                        }
2166                    } else {
2167                        makeA2dpDeviceUnavailableNow(address);
2168                    }
2169                } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
2170                    if (btDevice.isBluetoothDock()) {
2171                        // this could be a reconnection after a transient disconnection
2172                        cancelA2dpDeviceTimeout();
2173                        mDockAddress = address;
2174                    } else {
2175                        // this could be a connection of another A2DP device before the timeout of
2176                        // a dock: cancel the dock timeout, and make the dock unavailable now
2177                        if(hasScheduledA2dpDockTimeout()) {
2178                            cancelA2dpDeviceTimeout();
2179                            makeA2dpDeviceUnavailableNow(mDockAddress);
2180                        }
2181                    }
2182                    makeA2dpDeviceAvailable(address);
2183                }
2184            } else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
2185                int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
2186                                               BluetoothProfile.STATE_DISCONNECTED);
2187                int device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
2188                BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
2189                String address = null;
2190                if (btDevice != null) {
2191                    address = btDevice.getAddress();
2192                    BluetoothClass btClass = btDevice.getBluetoothClass();
2193                    if (btClass != null) {
2194                        switch (btClass.getDeviceClass()) {
2195                        case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET:
2196                        case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
2197                            device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2198                            break;
2199                        case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO:
2200                            device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2201                            break;
2202                        }
2203                    }
2204                }
2205
2206                boolean isConnected = (mConnectedDevices.containsKey(device) &&
2207                                       mConnectedDevices.get(device).equals(address));
2208
2209                synchronized (mScoClients) {
2210                    if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
2211                        AudioSystem.setDeviceConnectionState(device,
2212                                                             AudioSystem.DEVICE_STATE_UNAVAILABLE,
2213                                                             address);
2214                        mConnectedDevices.remove(device);
2215                        mBluetoothHeadsetDevice = null;
2216                        clearAllScoClients(null, false);
2217                        mScoAudioState = SCO_STATE_INACTIVE;
2218                    } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
2219                        AudioSystem.setDeviceConnectionState(device,
2220                                                             AudioSystem.DEVICE_STATE_AVAILABLE,
2221                                                             address);
2222                        mConnectedDevices.put(new Integer(device), address);
2223                        mBluetoothHeadsetDevice = btDevice;
2224                    }
2225                }
2226            } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
2227                int state = intent.getIntExtra("state", 0);
2228                int microphone = intent.getIntExtra("microphone", 0);
2229
2230                if (microphone != 0) {
2231                    boolean isConnected =
2232                        mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADSET);
2233                    if (state == 0 && isConnected) {
2234                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,
2235                                AudioSystem.DEVICE_STATE_UNAVAILABLE,
2236                                "");
2237                        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADSET);
2238                    } else if (state == 1 && !isConnected)  {
2239                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,
2240                                AudioSystem.DEVICE_STATE_AVAILABLE,
2241                                "");
2242                        mConnectedDevices.put(
2243                                new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADSET), "");
2244                    }
2245                } else {
2246                    boolean isConnected =
2247                        mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE);
2248                    if (state == 0 && isConnected) {
2249                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE,
2250                                AudioSystem.DEVICE_STATE_UNAVAILABLE,
2251                                "");
2252                        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE);
2253                    } else if (state == 1 && !isConnected)  {
2254                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE,
2255                                AudioSystem.DEVICE_STATE_AVAILABLE,
2256                                "");
2257                        mConnectedDevices.put(
2258                                new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE), "");
2259                    }
2260                }
2261            } else if (action.equals(Intent.ACTION_USB_ANLG_HEADSET_PLUG)) {
2262                int state = intent.getIntExtra("state", 0);
2263                Log.v(TAG, "Broadcast Receiver: Got ACTION_USB_ANLG_HEADSET_PLUG, state = "+state);
2264                boolean isConnected =
2265                    mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET);
2266                if (state == 0 && isConnected) {
2267                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET,
2268                                                         AudioSystem.DEVICE_STATE_UNAVAILABLE, "");
2269                    mConnectedDevices.remove(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET);
2270                } else if (state == 1 && !isConnected)  {
2271                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET,
2272                                                         AudioSystem.DEVICE_STATE_AVAILABLE, "");
2273                    mConnectedDevices.put(
2274                            new Integer(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET), "");
2275                }
2276            } else if (action.equals(Intent.ACTION_HDMI_AUDIO_PLUG)) {
2277                int state = intent.getIntExtra("state", 0);
2278                Log.v(TAG, "Broadcast Receiver: Got ACTION_HDMI_AUDIO_PLUG, state = "+state);
2279                boolean isConnected =
2280                    mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_AUX_DIGITAL);
2281                if (state == 0 && isConnected) {
2282                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_AUX_DIGITAL,
2283                                                         AudioSystem.DEVICE_STATE_UNAVAILABLE, "");
2284                    mConnectedDevices.remove(AudioSystem.DEVICE_OUT_AUX_DIGITAL);
2285                } else if (state == 1 && !isConnected)  {
2286                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_AUX_DIGITAL,
2287                                                         AudioSystem.DEVICE_STATE_AVAILABLE, "");
2288                    mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_AUX_DIGITAL), "");
2289                }
2290            } else if (action.equals(Intent.ACTION_USB_DGTL_HEADSET_PLUG)) {
2291                int state = intent.getIntExtra("state", 0);
2292                Log.v(TAG, "Broadcast Receiver: Got ACTION_USB_DGTL_HEADSET_PLUG, state = "+state);
2293                boolean isConnected =
2294                    mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET);
2295                if (state == 0 && isConnected) {
2296                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET,
2297                                                         AudioSystem.DEVICE_STATE_UNAVAILABLE, "");
2298                    mConnectedDevices.remove(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET);
2299                } else if (state == 1 && !isConnected)  {
2300                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET,
2301                                                         AudioSystem.DEVICE_STATE_AVAILABLE, "");
2302                    mConnectedDevices.put(
2303                            new Integer(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET), "");
2304                }
2305            } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) {
2306                boolean broadcast = false;
2307                int audioState = AudioManager.SCO_AUDIO_STATE_ERROR;
2308                synchronized (mScoClients) {
2309                    int btState = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1);
2310                    if (!mScoClients.isEmpty() && mScoAudioState == SCO_STATE_ACTIVE_INTERNAL) {
2311                        broadcast = true;
2312                    }
2313                    switch (btState) {
2314                    case BluetoothHeadset.STATE_AUDIO_CONNECTED:
2315                        audioState = AudioManager.SCO_AUDIO_STATE_CONNECTED;
2316                        if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL) {
2317                            mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
2318                        }
2319                        break;
2320                    case BluetoothHeadset.STATE_AUDIO_DISCONNECTED:
2321                        audioState = AudioManager.SCO_AUDIO_STATE_DISCONNECTED;
2322                        mScoAudioState = SCO_STATE_INACTIVE;
2323                        break;
2324                    case BluetoothHeadset.STATE_AUDIO_CONNECTING:
2325                        if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL) {
2326                            mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
2327                        }
2328                    default:
2329                        // do not broadcast CONNECTING or invalid state
2330                        broadcast = false;
2331                        break;
2332                    }
2333                }
2334                if (broadcast) {
2335                    Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
2336                    newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, audioState);
2337                    mContext.sendStickyBroadcast(newIntent);
2338                }
2339            } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
2340                mBootCompleted = true;
2341                sendMsg(mAudioHandler, MSG_LOAD_SOUND_EFFECTS, SHARED_MSG, SENDMSG_NOOP,
2342                        0, 0, null, 0);
2343                Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
2344                newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,
2345                        AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
2346                mContext.sendStickyBroadcast(newIntent);
2347            }
2348        }
2349    }
2350
2351    //==========================================================================================
2352    // AudioFocus
2353    //==========================================================================================
2354
2355    /* constant to identify focus stack entry that is used to hold the focus while the phone
2356     * is ringing or during a call
2357     */
2358    private final static String IN_VOICE_COMM_FOCUS_ID = "AudioFocus_For_Phone_Ring_And_Calls";
2359
2360    private final static Object mAudioFocusLock = new Object();
2361
2362    private final static Object mRingingLock = new Object();
2363
2364    private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
2365        @Override
2366        public void onCallStateChanged(int state, String incomingNumber) {
2367            if (state == TelephonyManager.CALL_STATE_RINGING) {
2368                //Log.v(TAG, " CALL_STATE_RINGING");
2369                synchronized(mRingingLock) {
2370                    mIsRinging = true;
2371                }
2372            } else if ((state == TelephonyManager.CALL_STATE_OFFHOOK)
2373                    || (state == TelephonyManager.CALL_STATE_IDLE)) {
2374                synchronized(mRingingLock) {
2375                    mIsRinging = false;
2376                }
2377            }
2378        }
2379    };
2380
2381    private void notifyTopOfAudioFocusStack() {
2382        // notify the top of the stack it gained focus
2383        if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) {
2384            if (canReassignAudioFocus()) {
2385                try {
2386                    mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange(
2387                            AudioManager.AUDIOFOCUS_GAIN, mFocusStack.peek().mClientId);
2388                } catch (RemoteException e) {
2389                    Log.e(TAG, "Failure to signal gain of audio control focus due to "+ e);
2390                    e.printStackTrace();
2391                }
2392            }
2393        }
2394    }
2395
2396    private static class FocusStackEntry {
2397        public int mStreamType = -1;// no stream type
2398        public boolean mIsTransportControlReceiver = false;
2399        public IAudioFocusDispatcher mFocusDispatcher = null;
2400        public IBinder mSourceRef = null;
2401        public String mClientId;
2402        public int mFocusChangeType;
2403
2404        public FocusStackEntry() {
2405        }
2406
2407        public FocusStackEntry(int streamType, int duration, boolean isTransportControlReceiver,
2408                IAudioFocusDispatcher afl, IBinder source, String id) {
2409            mStreamType = streamType;
2410            mIsTransportControlReceiver = isTransportControlReceiver;
2411            mFocusDispatcher = afl;
2412            mSourceRef = source;
2413            mClientId = id;
2414            mFocusChangeType = duration;
2415        }
2416    }
2417
2418    private Stack<FocusStackEntry> mFocusStack = new Stack<FocusStackEntry>();
2419
2420    /**
2421     * Helper function:
2422     * Display in the log the current entries in the audio focus stack
2423     */
2424    private void dumpFocusStack(PrintWriter pw) {
2425        pw.println("\nAudio Focus stack entries:");
2426        synchronized(mAudioFocusLock) {
2427            Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
2428            while(stackIterator.hasNext()) {
2429                FocusStackEntry fse = stackIterator.next();
2430                pw.println("     source:" + fse.mSourceRef + " -- client: " + fse.mClientId
2431                        + " -- duration: " +fse.mFocusChangeType);
2432            }
2433        }
2434    }
2435
2436    /**
2437     * Helper function:
2438     * Remove a focus listener from the focus stack.
2439     * @param focusListenerToRemove the focus listener
2440     * @param signal if true and the listener was at the top of the focus stack, i.e. it was holding
2441     *   focus, notify the next item in the stack it gained focus.
2442     */
2443    private void removeFocusStackEntry(String clientToRemove, boolean signal) {
2444        // is the current top of the focus stack abandoning focus? (because of death or request)
2445        if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientToRemove))
2446        {
2447            //Log.i(TAG, "   removeFocusStackEntry() removing top of stack");
2448            mFocusStack.pop();
2449            if (signal) {
2450                // notify the new top of the stack it gained focus
2451                notifyTopOfAudioFocusStack();
2452            }
2453        } else {
2454            // focus is abandoned by a client that's not at the top of the stack,
2455            // no need to update focus.
2456            Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
2457            while(stackIterator.hasNext()) {
2458                FocusStackEntry fse = (FocusStackEntry)stackIterator.next();
2459                if(fse.mClientId.equals(clientToRemove)) {
2460                    Log.i(TAG, " AudioFocus  abandonAudioFocus(): removing entry for "
2461                            + fse.mClientId);
2462                    mFocusStack.remove(fse);
2463                }
2464            }
2465        }
2466    }
2467
2468    /**
2469     * Helper function:
2470     * Remove focus listeners from the focus stack for a particular client.
2471     */
2472    private void removeFocusStackEntryForClient(IBinder cb) {
2473        // is the owner of the audio focus part of the client to remove?
2474        boolean isTopOfStackForClientToRemove = !mFocusStack.isEmpty() &&
2475                mFocusStack.peek().mSourceRef.equals(cb);
2476        Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
2477        while(stackIterator.hasNext()) {
2478            FocusStackEntry fse = (FocusStackEntry)stackIterator.next();
2479            if(fse.mSourceRef.equals(cb)) {
2480                Log.i(TAG, " AudioFocus  abandonAudioFocus(): removing entry for "
2481                        + fse.mClientId);
2482                mFocusStack.remove(fse);
2483            }
2484        }
2485        if (isTopOfStackForClientToRemove) {
2486            // we removed an entry at the top of the stack:
2487            //  notify the new top of the stack it gained focus.
2488            notifyTopOfAudioFocusStack();
2489        }
2490    }
2491
2492    /**
2493     * Helper function:
2494     * Returns true if the system is in a state where the focus can be reevaluated, false otherwise.
2495     */
2496    private boolean canReassignAudioFocus() {
2497        // focus requests are rejected during a phone call or when the phone is ringing
2498        // this is equivalent to IN_VOICE_COMM_FOCUS_ID having the focus
2499        if (!mFocusStack.isEmpty() && IN_VOICE_COMM_FOCUS_ID.equals(mFocusStack.peek().mClientId)) {
2500            return false;
2501        }
2502        return true;
2503    }
2504
2505    /**
2506     * Inner class to monitor audio focus client deaths, and remove them from the audio focus
2507     * stack if necessary.
2508     */
2509    private class AudioFocusDeathHandler implements IBinder.DeathRecipient {
2510        private IBinder mCb; // To be notified of client's death
2511
2512        AudioFocusDeathHandler(IBinder cb) {
2513            mCb = cb;
2514        }
2515
2516        public void binderDied() {
2517            synchronized(mAudioFocusLock) {
2518                Log.w(TAG, "  AudioFocus   audio focus client died");
2519                removeFocusStackEntryForClient(mCb);
2520            }
2521        }
2522
2523        public IBinder getBinder() {
2524            return mCb;
2525        }
2526    }
2527
2528
2529    /** @see AudioManager#requestAudioFocus(IAudioFocusDispatcher, int, int) */
2530    public int requestAudioFocus(int mainStreamType, int focusChangeHint, IBinder cb,
2531            IAudioFocusDispatcher fd, String clientId) {
2532        Log.i(TAG, " AudioFocus  requestAudioFocus() from " + clientId);
2533        // the main stream type for the audio focus request is currently not used. It may
2534        // potentially be used to handle multiple stream type-dependent audio focuses.
2535
2536        // we need a valid binder callback for clients other than the AudioService's phone
2537        // state listener
2538        if (!IN_VOICE_COMM_FOCUS_ID.equals(clientId) && ((cb == null) || !cb.pingBinder())) {
2539            Log.i(TAG, " AudioFocus  DOA client for requestAudioFocus(), exiting");
2540            return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
2541        }
2542
2543        synchronized(mAudioFocusLock) {
2544            if (!canReassignAudioFocus()) {
2545                return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
2546            }
2547
2548            if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientId)) {
2549                // if focus is already owned by this client and the reason for acquiring the focus
2550                // hasn't changed, don't do anything
2551                if (mFocusStack.peek().mFocusChangeType == focusChangeHint) {
2552                    return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
2553                }
2554                // the reason for the audio focus request has changed: remove the current top of
2555                // stack and respond as if we had a new focus owner
2556                mFocusStack.pop();
2557            }
2558
2559            // notify current top of stack it is losing focus
2560            if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) {
2561                try {
2562                    mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange(
2563                            -1 * focusChangeHint, // loss and gain codes are inverse of each other
2564                            mFocusStack.peek().mClientId);
2565                } catch (RemoteException e) {
2566                    Log.e(TAG, " Failure to signal loss of focus due to "+ e);
2567                    e.printStackTrace();
2568                }
2569            }
2570
2571            // focus requester might already be somewhere below in the stack, remove it
2572            removeFocusStackEntry(clientId, false);
2573
2574            // push focus requester at the top of the audio focus stack
2575            mFocusStack.push(new FocusStackEntry(mainStreamType, focusChangeHint, false, fd, cb,
2576                    clientId));
2577        }//synchronized(mAudioFocusLock)
2578
2579        // handle the potential premature death of the new holder of the focus
2580        // (premature death == death before abandoning focus) for a client which is not the
2581        // AudioService's phone state listener
2582        if (!IN_VOICE_COMM_FOCUS_ID.equals(clientId)) {
2583            // Register for client death notification
2584            AudioFocusDeathHandler afdh = new AudioFocusDeathHandler(cb);
2585            try {
2586                cb.linkToDeath(afdh, 0);
2587            } catch (RemoteException e) {
2588                // client has already died!
2589                Log.w(TAG, "AudioFocus  requestAudioFocus() could not link to "+cb+" binder death");
2590            }
2591        }
2592
2593        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
2594    }
2595
2596    /** @see AudioManager#abandonAudioFocus(IAudioFocusDispatcher) */
2597    public int abandonAudioFocus(IAudioFocusDispatcher fl, String clientId) {
2598        Log.i(TAG, " AudioFocus  abandonAudioFocus() from " + clientId);
2599        try {
2600            // this will take care of notifying the new focus owner if needed
2601            synchronized(mAudioFocusLock) {
2602                removeFocusStackEntry(clientId, true);
2603            }
2604        } catch (java.util.ConcurrentModificationException cme) {
2605            // Catching this exception here is temporary. It is here just to prevent
2606            // a crash seen when the "Silent" notification is played. This is believed to be fixed
2607            // but this try catch block is left just to be safe.
2608            Log.e(TAG, "FATAL EXCEPTION AudioFocus  abandonAudioFocus() caused " + cme);
2609            cme.printStackTrace();
2610        }
2611
2612        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
2613    }
2614
2615
2616    public void unregisterAudioFocusClient(String clientId) {
2617        synchronized(mAudioFocusLock) {
2618            removeFocusStackEntry(clientId, false);
2619        }
2620    }
2621
2622
2623    //==========================================================================================
2624    // RemoteControl
2625    //==========================================================================================
2626    /**
2627     * Receiver for media button intents. Handles the dispatching of the media button event
2628     * to one of the registered listeners, or if there was none, resumes the intent broadcast
2629     * to the rest of the system.
2630     */
2631    private class MediaButtonBroadcastReceiver extends BroadcastReceiver {
2632        @Override
2633        public void onReceive(Context context, Intent intent) {
2634            String action = intent.getAction();
2635            if (!Intent.ACTION_MEDIA_BUTTON.equals(action)) {
2636                return;
2637            }
2638            KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
2639            if (event != null) {
2640                // if in a call or ringing, do not break the current phone app behavior
2641                // TODO modify this to let the phone app specifically get the RC focus
2642                //      add modify the phone app to take advantage of the new API
2643                synchronized(mRingingLock) {
2644                    if (mIsRinging || (getMode() == AudioSystem.MODE_IN_CALL) ||
2645                            (getMode() == AudioSystem.MODE_IN_COMMUNICATION) ||
2646                            (getMode() == AudioSystem.MODE_RINGTONE) ) {
2647                        return;
2648                    }
2649                }
2650                synchronized(mRCStack) {
2651                    if (!mRCStack.empty()) {
2652                        // create a new intent specifically aimed at the current registered listener
2653                        Intent targetedIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
2654                        targetedIntent.putExtras(intent.getExtras());
2655                        targetedIntent.setComponent(mRCStack.peek().mReceiverComponent);
2656                        // trap the current broadcast
2657                        abortBroadcast();
2658                        //Log.v(TAG, " Sending intent" + targetedIntent);
2659                        context.sendBroadcast(targetedIntent, null);
2660                    }
2661                }
2662            }
2663        }
2664    }
2665
2666    private static class RemoteControlStackEntry {
2667        public ComponentName mReceiverComponent;// always non null
2668        // TODO implement registration expiration?
2669        //public int mRegistrationTime;
2670
2671        public RemoteControlStackEntry() {
2672        }
2673
2674        public RemoteControlStackEntry(ComponentName r) {
2675            mReceiverComponent = r;
2676        }
2677    }
2678
2679    private Stack<RemoteControlStackEntry> mRCStack = new Stack<RemoteControlStackEntry>();
2680
2681    /**
2682     * Helper function:
2683     * Display in the log the current entries in the remote control focus stack
2684     */
2685    private void dumpRCStack(PrintWriter pw) {
2686        pw.println("\nRemote Control stack entries:");
2687        synchronized(mRCStack) {
2688            Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
2689            while(stackIterator.hasNext()) {
2690                RemoteControlStackEntry fse = stackIterator.next();
2691                pw.println("     receiver:" + fse.mReceiverComponent);
2692            }
2693        }
2694    }
2695
2696    /**
2697     * Helper function:
2698     * Set the new remote control receiver at the top of the RC focus stack
2699     */
2700    private void pushMediaButtonReceiver(ComponentName newReceiver) {
2701        // already at top of stack?
2702        if (!mRCStack.empty() && mRCStack.peek().mReceiverComponent.equals(newReceiver)) {
2703            return;
2704        }
2705        Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
2706        while(stackIterator.hasNext()) {
2707            RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
2708            if(rcse.mReceiverComponent.equals(newReceiver)) {
2709                mRCStack.remove(rcse);
2710                break;
2711            }
2712        }
2713        mRCStack.push(new RemoteControlStackEntry(newReceiver));
2714    }
2715
2716    /**
2717     * Helper function:
2718     * Remove the remote control receiver from the RC focus stack
2719     */
2720    private void removeMediaButtonReceiver(ComponentName newReceiver) {
2721        Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
2722        while(stackIterator.hasNext()) {
2723            RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
2724            if(rcse.mReceiverComponent.equals(newReceiver)) {
2725                mRCStack.remove(rcse);
2726                break;
2727            }
2728        }
2729    }
2730
2731
2732    /** see AudioManager.registerMediaButtonEventReceiver(ComponentName eventReceiver) */
2733    public void registerMediaButtonEventReceiver(ComponentName eventReceiver) {
2734        Log.i(TAG, "  Remote Control   registerMediaButtonEventReceiver() for " + eventReceiver);
2735
2736        synchronized(mRCStack) {
2737            pushMediaButtonReceiver(eventReceiver);
2738        }
2739    }
2740
2741    /** see AudioManager.unregisterMediaButtonEventReceiver(ComponentName eventReceiver) */
2742    public void unregisterMediaButtonEventReceiver(ComponentName eventReceiver) {
2743        Log.i(TAG, "  Remote Control   unregisterMediaButtonEventReceiver() for " + eventReceiver);
2744
2745        synchronized(mRCStack) {
2746            removeMediaButtonReceiver(eventReceiver);
2747        }
2748    }
2749
2750
2751    @Override
2752    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2753        // TODO probably a lot more to do here than just the audio focus and remote control stacks
2754        dumpFocusStack(pw);
2755        dumpRCStack(pw);
2756    }
2757
2758
2759}
2760