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