AudioService.java revision b782e8d71e693984cc5236f1cf08e0c3c11a4050
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 static android.media.AudioManager.RINGER_MODE_NORMAL;
20import static android.media.AudioManager.RINGER_MODE_SILENT;
21import static android.media.AudioManager.RINGER_MODE_VIBRATE;
22
23import android.app.ActivityManagerNative;
24import android.app.KeyguardManager;
25import android.app.PendingIntent;
26import android.app.PendingIntent.CanceledException;
27import android.bluetooth.BluetoothA2dp;
28import android.bluetooth.BluetoothAdapter;
29import android.bluetooth.BluetoothClass;
30import android.bluetooth.BluetoothDevice;
31import android.bluetooth.BluetoothHeadset;
32import android.bluetooth.BluetoothProfile;
33import android.content.BroadcastReceiver;
34import android.content.ComponentName;
35import android.content.ContentResolver;
36import android.content.Context;
37import android.content.Intent;
38import android.content.IntentFilter;
39import android.content.pm.PackageManager;
40import android.database.ContentObserver;
41import android.media.MediaPlayer.OnCompletionListener;
42import android.media.MediaPlayer.OnErrorListener;
43import android.os.Binder;
44import android.os.Bundle;
45import android.os.Environment;
46import android.os.Handler;
47import android.os.IBinder;
48import android.os.Looper;
49import android.os.Message;
50import android.os.RemoteException;
51import android.os.ServiceManager;
52import android.os.SystemProperties;
53import android.provider.Settings;
54import android.provider.Settings.System;
55import android.telephony.PhoneStateListener;
56import android.telephony.TelephonyManager;
57import android.util.Log;
58import android.view.KeyEvent;
59import android.view.VolumePanel;
60
61import com.android.internal.telephony.ITelephony;
62
63import java.io.FileDescriptor;
64import java.io.IOException;
65import java.io.PrintWriter;
66import java.util.ArrayList;
67import java.util.HashMap;
68import java.util.Iterator;
69import java.util.List;
70import java.util.Map;
71import java.util.NoSuchElementException;
72import java.util.Set;
73import java.util.Stack;
74
75/**
76 * The implementation of the volume manager service.
77 * <p>
78 * This implementation focuses on delivering a responsive UI. Most methods are
79 * asynchronous to external calls. For example, the task of setting a volume
80 * will update our internal state, but in a separate thread will set the system
81 * volume and later persist to the database. Similarly, setting the ringer mode
82 * will update the state and broadcast a change and in a separate thread later
83 * persist the ringer mode.
84 *
85 * @hide
86 */
87public class AudioService extends IAudioService.Stub {
88
89    private static final String TAG = "AudioService";
90
91    /** Debug remote control client/display feature */
92    protected static final boolean DEBUG_RC = false;
93
94    /** How long to delay before persisting a change in volume/ringer mode. */
95    private static final int PERSIST_DELAY = 3000;
96
97    private Context mContext;
98    private ContentResolver mContentResolver;
99    private boolean mVoiceCapable;
100
101    /** The UI */
102    private VolumePanel mVolumePanel;
103
104    // sendMsg() flags
105    /** Used when a message should be shared across all stream types. */
106    private static final int SHARED_MSG = -1;
107    /** If the msg is already queued, replace it with this one. */
108    private static final int SENDMSG_REPLACE = 0;
109    /** If the msg is already queued, ignore this one and leave the old. */
110    private static final int SENDMSG_NOOP = 1;
111    /** If the msg is already queued, queue this one and leave the old. */
112    private static final int SENDMSG_QUEUE = 2;
113
114    // AudioHandler message.whats
115    private static final int MSG_SET_SYSTEM_VOLUME = 0;
116    private static final int MSG_PERSIST_VOLUME = 1;
117    private static final int MSG_PERSIST_RINGER_MODE = 3;
118    private static final int MSG_PERSIST_VIBRATE_SETTING = 4;
119    private static final int MSG_MEDIA_SERVER_DIED = 5;
120    private static final int MSG_MEDIA_SERVER_STARTED = 6;
121    private static final int MSG_PLAY_SOUND_EFFECT = 7;
122    private static final int MSG_BTA2DP_DOCK_TIMEOUT = 8;
123    private static final int MSG_LOAD_SOUND_EFFECTS = 9;
124    private static final int MSG_SET_FORCE_USE = 10;
125    private static final int MSG_PERSIST_MEDIABUTTONRECEIVER = 11;
126    private static final int MSG_BT_HEADSET_CNCT_FAILED = 12;
127    private static final int MSG_RCDISPLAY_CLEAR = 13;
128    private static final int MSG_RCDISPLAY_UPDATE = 14;
129
130    private static final int BTA2DP_DOCK_TIMEOUT_MILLIS = 8000;
131    // Timeout for connection to bluetooth headset service
132    private static final int BT_HEADSET_CNCT_TIMEOUT_MS = 3000;
133
134    // Amount to raise/lower master volume
135    // FIXME - this should probably be in a resource
136    private static final float MASTER_VOLUME_INCREMENT = 0.05f;
137
138    /** @see AudioSystemThread */
139    private AudioSystemThread mAudioSystemThread;
140    /** @see AudioHandler */
141    private AudioHandler mAudioHandler;
142    /** @see VolumeStreamState */
143    private VolumeStreamState[] mStreamStates;
144    private SettingsObserver mSettingsObserver;
145
146    private int mMode;
147    private Object mSettingsLock = new Object();
148    private boolean mMediaServerOk;
149
150    private SoundPool mSoundPool;
151    private Object mSoundEffectsLock = new Object();
152    private static final int NUM_SOUNDPOOL_CHANNELS = 4;
153    private static final int SOUND_EFFECT_VOLUME = 1000;
154
155    // Internally master volume is a float in the 0.0 - 1.0 range,
156    // but to support integer based AudioManager API we translate it to 0 - 100
157    private static final int MAX_MASTER_VOLUME = 100;
158
159    /* Sound effect file names  */
160    private static final String SOUND_EFFECTS_PATH = "/media/audio/ui/";
161    private static final String[] SOUND_EFFECT_FILES = new String[] {
162        "Effect_Tick.ogg",
163        "KeypressStandard.ogg",
164        "KeypressSpacebar.ogg",
165        "KeypressDelete.ogg",
166        "KeypressReturn.ogg"
167    };
168
169    /* Sound effect file name mapping sound effect id (AudioManager.FX_xxx) to
170     * file index in SOUND_EFFECT_FILES[] (first column) and indicating if effect
171     * uses soundpool (second column) */
172    private int[][] SOUND_EFFECT_FILES_MAP = new int[][] {
173        {0, -1},  // FX_KEY_CLICK
174        {0, -1},  // FX_FOCUS_NAVIGATION_UP
175        {0, -1},  // FX_FOCUS_NAVIGATION_DOWN
176        {0, -1},  // FX_FOCUS_NAVIGATION_LEFT
177        {0, -1},  // FX_FOCUS_NAVIGATION_RIGHT
178        {1, -1},  // FX_KEYPRESS_STANDARD
179        {2, -1},  // FX_KEYPRESS_SPACEBAR
180        {3, -1},  // FX_FOCUS_DELETE
181        {4, -1}   // FX_FOCUS_RETURN
182    };
183
184   /** @hide Maximum volume index values for audio streams */
185    private int[] MAX_STREAM_VOLUME = new int[] {
186        5,  // STREAM_VOICE_CALL
187        7,  // STREAM_SYSTEM
188        7,  // STREAM_RING
189        15, // STREAM_MUSIC
190        7,  // STREAM_ALARM
191        7,  // STREAM_NOTIFICATION
192        15, // STREAM_BLUETOOTH_SCO
193        7,  // STREAM_SYSTEM_ENFORCED
194        15, // STREAM_DTMF
195        15  // STREAM_TTS
196    };
197    /* STREAM_VOLUME_ALIAS[] indicates for each stream if it uses the volume settings
198     * of another stream: This avoids multiplying the volume settings for hidden
199     * stream types that follow other stream behavior for volume settings
200     * NOTE: do not create loops in aliases! */
201    private int[] STREAM_VOLUME_ALIAS = new int[] {
202        AudioSystem.STREAM_VOICE_CALL,  // STREAM_VOICE_CALL
203        AudioSystem.STREAM_SYSTEM,  // STREAM_SYSTEM
204        AudioSystem.STREAM_RING,  // STREAM_RING
205        AudioSystem.STREAM_MUSIC, // STREAM_MUSIC
206        AudioSystem.STREAM_ALARM,  // STREAM_ALARM
207        AudioSystem.STREAM_RING,   // STREAM_NOTIFICATION
208        AudioSystem.STREAM_BLUETOOTH_SCO, // STREAM_BLUETOOTH_SCO
209        AudioSystem.STREAM_SYSTEM,  // STREAM_SYSTEM_ENFORCED
210        AudioSystem.STREAM_VOICE_CALL, // STREAM_DTMF
211        AudioSystem.STREAM_MUSIC  // STREAM_TTS
212    };
213
214    private AudioSystem.ErrorCallback mAudioSystemCallback = new AudioSystem.ErrorCallback() {
215        public void onError(int error) {
216            switch (error) {
217            case AudioSystem.AUDIO_STATUS_SERVER_DIED:
218                if (mMediaServerOk) {
219                    sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
220                            null, 1500);
221                    mMediaServerOk = false;
222                }
223                break;
224            case AudioSystem.AUDIO_STATUS_OK:
225                if (!mMediaServerOk) {
226                    sendMsg(mAudioHandler, MSG_MEDIA_SERVER_STARTED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
227                            null, 0);
228                    mMediaServerOk = true;
229                }
230                break;
231            default:
232                break;
233            }
234       }
235    };
236
237    /**
238     * Current ringer mode from one of {@link AudioManager#RINGER_MODE_NORMAL},
239     * {@link AudioManager#RINGER_MODE_SILENT}, or
240     * {@link AudioManager#RINGER_MODE_VIBRATE}.
241     */
242    private int mRingerMode;
243
244    /** @see System#MODE_RINGER_STREAMS_AFFECTED */
245    private int mRingerModeAffectedStreams;
246
247    // Streams currently muted by ringer mode
248    private int mRingerModeMutedStreams;
249
250    /** @see System#MUTE_STREAMS_AFFECTED */
251    private int mMuteAffectedStreams;
252
253    /**
254     * Has multiple bits per vibrate type to indicate the type's vibrate
255     * setting. See {@link #setVibrateSetting(int, int)}.
256     * <p>
257     * NOTE: This is not the final decision of whether vibrate is on/off for the
258     * type since it depends on the ringer mode. See {@link #shouldVibrate(int)}.
259     */
260    private int mVibrateSetting;
261
262    // Broadcast receiver for device connections intent broadcasts
263    private final BroadcastReceiver mReceiver = new AudioServiceBroadcastReceiver();
264
265    //  Broadcast receiver for media button broadcasts (separate from mReceiver to
266    //  independently change its priority)
267    private final BroadcastReceiver mMediaButtonReceiver = new MediaButtonBroadcastReceiver();
268
269    // Used to alter media button redirection when the phone is ringing.
270    private boolean mIsRinging = false;
271
272    // Devices currently connected
273    private HashMap <Integer, String> mConnectedDevices = new HashMap <Integer, String>();
274
275    // Forced device usage for communications
276    private int mForcedUseForComm;
277
278    // True if we have master volume support
279    private final boolean mUseMasterVolume;
280
281    // List of binder death handlers for setMode() client processes.
282    // The last process to have called setMode() is at the top of the list.
283    private ArrayList <SetModeDeathHandler> mSetModeDeathHandlers = new ArrayList <SetModeDeathHandler>();
284
285    // List of clients having issued a SCO start request
286    private ArrayList <ScoClient> mScoClients = new ArrayList <ScoClient>();
287
288    // BluetoothHeadset API to control SCO connection
289    private BluetoothHeadset mBluetoothHeadset;
290
291    // Bluetooth headset device
292    private BluetoothDevice mBluetoothHeadsetDevice;
293
294    // Indicate if SCO audio connection is currently active and if the initiator is
295    // audio service (internal) or bluetooth headset (external)
296    private int mScoAudioState;
297    // SCO audio state is not active
298    private static final int SCO_STATE_INACTIVE = 0;
299    // SCO audio activation request waiting for headset service to connect
300    private static final int SCO_STATE_ACTIVATE_REQ = 1;
301    // SCO audio state is active or starting due to a local request to start a virtual call
302    private static final int SCO_STATE_ACTIVE_INTERNAL = 3;
303    // SCO audio deactivation request waiting for headset service to connect
304    private static final int SCO_STATE_DEACTIVATE_REQ = 5;
305
306    // SCO audio state is active due to an action in BT handsfree (either voice recognition or
307    // in call audio)
308    private static final int SCO_STATE_ACTIVE_EXTERNAL = 2;
309    // Deactivation request for all SCO connections (initiated by audio mode change)
310    // waiting for headset service to connect
311    private static final int SCO_STATE_DEACTIVATE_EXT_REQ = 4;
312
313    // Current connection state indicated by bluetooth headset
314    private int mScoConnectionState;
315
316    // true if boot sequence has been completed
317    private boolean mBootCompleted;
318    // listener for SoundPool sample load completion indication
319    private SoundPoolCallback mSoundPoolCallBack;
320    // thread for SoundPool listener
321    private SoundPoolListenerThread mSoundPoolListenerThread;
322    // message looper for SoundPool listener
323    private Looper mSoundPoolLooper = null;
324    // default volume applied to sound played with playSoundEffect()
325    private static final int SOUND_EFFECT_DEFAULT_VOLUME_DB = -20;
326    // volume applied to sound played with playSoundEffect() read from ro.config.sound_fx_volume
327    private int SOUND_EFFECT_VOLUME_DB;
328    // getActiveStreamType() will return STREAM_NOTIFICATION during this period after a notification
329    // stopped
330    private static final int NOTIFICATION_VOLUME_DELAY_MS = 5000;
331    // previous volume adjustment direction received by checkForRingerModeChange()
332    private int mPrevVolDirection = AudioManager.ADJUST_SAME;
333    // Keyguard manager proxy
334    private KeyguardManager mKeyguardManager;
335
336    ///////////////////////////////////////////////////////////////////////////
337    // Construction
338    ///////////////////////////////////////////////////////////////////////////
339
340    /** @hide */
341    public AudioService(Context context) {
342        mContext = context;
343        mContentResolver = context.getContentResolver();
344        mVoiceCapable = mContext.getResources().getBoolean(
345                com.android.internal.R.bool.config_voice_capable);
346
347       // Intialized volume
348        MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = SystemProperties.getInt(
349            "ro.config.vc_call_vol_steps",
350           MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]);
351
352        SOUND_EFFECT_VOLUME_DB = SystemProperties.getInt(
353                "ro.config.sound_fx_volume",
354                SOUND_EFFECT_DEFAULT_VOLUME_DB);
355
356        mVolumePanel = new VolumePanel(context, this);
357        mForcedUseForComm = AudioSystem.FORCE_NONE;
358        createAudioSystemThread();
359        readPersistedSettings();
360        mSettingsObserver = new SettingsObserver();
361        createStreamStates();
362
363        mMode = AudioSystem.MODE_NORMAL;
364        mMediaServerOk = true;
365
366        // Call setRingerModeInt() to apply correct mute
367        // state on streams affected by ringer mode.
368        mRingerModeMutedStreams = 0;
369        setRingerModeInt(getRingerMode(), false);
370
371        AudioSystem.setErrorCallback(mAudioSystemCallback);
372
373        // Register for device connection intent broadcasts.
374        IntentFilter intentFilter =
375                new IntentFilter(Intent.ACTION_HEADSET_PLUG);
376
377        intentFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
378        intentFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
379        intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
380        intentFilter.addAction(Intent.ACTION_DOCK_EVENT);
381        intentFilter.addAction(Intent.ACTION_USB_ANLG_HEADSET_PLUG);
382        intentFilter.addAction(Intent.ACTION_USB_DGTL_HEADSET_PLUG);
383        intentFilter.addAction(Intent.ACTION_HDMI_AUDIO_PLUG);
384        intentFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
385        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
386        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
387        context.registerReceiver(mReceiver, intentFilter);
388
389        // Register for package removal intent broadcasts for media button receiver persistence
390        IntentFilter pkgFilter = new IntentFilter();
391        pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
392        pkgFilter.addDataScheme("package");
393        context.registerReceiver(mReceiver, pkgFilter);
394
395        // Register for media button intent broadcasts.
396        intentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
397        // Workaround for bug on priority setting
398        //intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
399        intentFilter.setPriority(Integer.MAX_VALUE);
400        context.registerReceiver(mMediaButtonReceiver, intentFilter);
401
402        // Register for phone state monitoring
403        TelephonyManager tmgr = (TelephonyManager)
404                context.getSystemService(Context.TELEPHONY_SERVICE);
405        tmgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
406
407        mUseMasterVolume = context.getResources().getBoolean(
408                com.android.internal.R.bool.config_useMasterVolume);
409        if (mUseMasterVolume) {
410            float volume = Settings.System.getFloat(mContentResolver,
411                    Settings.System.VOLUME_MASTER, -1.0f);
412            if (volume >= 0.0f) {
413                AudioSystem.setMasterVolume(volume);
414            }
415        }
416    }
417
418    private void createAudioSystemThread() {
419        mAudioSystemThread = new AudioSystemThread();
420        mAudioSystemThread.start();
421        waitForAudioHandlerCreation();
422    }
423
424    /** Waits for the volume handler to be created by the other thread. */
425    private void waitForAudioHandlerCreation() {
426        synchronized(this) {
427            while (mAudioHandler == null) {
428                try {
429                    // Wait for mAudioHandler to be set by the other thread
430                    wait();
431                } catch (InterruptedException e) {
432                    Log.e(TAG, "Interrupted while waiting on volume handler.");
433                }
434            }
435        }
436    }
437
438    private void createStreamStates() {
439        int numStreamTypes = AudioSystem.getNumStreamTypes();
440        VolumeStreamState[] streams = mStreamStates = new VolumeStreamState[numStreamTypes];
441
442        for (int i = 0; i < numStreamTypes; i++) {
443            streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[i]], i);
444        }
445
446        // Correct stream index values for streams with aliases
447        for (int i = 0; i < numStreamTypes; i++) {
448            if (STREAM_VOLUME_ALIAS[i] != i) {
449                int index = rescaleIndex(streams[i].mIndex, STREAM_VOLUME_ALIAS[i], i);
450                streams[i].mIndex = streams[i].getValidIndex(index);
451                setStreamVolumeIndex(i, index);
452                index = rescaleIndex(streams[i].mLastAudibleIndex, STREAM_VOLUME_ALIAS[i], i);
453                streams[i].mLastAudibleIndex = streams[i].getValidIndex(index);
454            }
455        }
456    }
457
458    private void readPersistedSettings() {
459        final ContentResolver cr = mContentResolver;
460
461        mRingerMode = System.getInt(cr, System.MODE_RINGER, AudioManager.RINGER_MODE_NORMAL);
462        // sanity check in case the settings are restored from a device with incompatible
463        // ringer modes
464        if (!AudioManager.isValidRingerMode(mRingerMode)) {
465            mRingerMode = AudioManager.RINGER_MODE_NORMAL;
466            System.putInt(cr, System.MODE_RINGER, mRingerMode);
467        }
468
469        mVibrateSetting = System.getInt(cr, System.VIBRATE_ON, 0);
470
471        // make sure settings for ringer mode are consistent with device type: non voice capable
472        // devices (tablets) include media stream in silent mode whereas phones don't.
473        mRingerModeAffectedStreams = Settings.System.getInt(cr,
474                Settings.System.MODE_RINGER_STREAMS_AFFECTED,
475                ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)|
476                 (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED)));
477        if (mVoiceCapable) {
478            mRingerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_MUSIC);
479        } else {
480            mRingerModeAffectedStreams |= (1 << AudioSystem.STREAM_MUSIC);
481        }
482        Settings.System.putInt(cr,
483                Settings.System.MODE_RINGER_STREAMS_AFFECTED, mRingerModeAffectedStreams);
484
485        mMuteAffectedStreams = System.getInt(cr,
486                System.MUTE_STREAMS_AFFECTED,
487                ((1 << AudioSystem.STREAM_MUSIC)|(1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_SYSTEM)));
488
489        // Each stream will read its own persisted settings
490
491        // Broadcast the sticky intent
492        broadcastRingerMode();
493
494        // Broadcast vibrate settings
495        broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);
496        broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION);
497
498        // Restore the default media button receiver from the system settings
499        restoreMediaButtonReceiver();
500    }
501
502    private void setStreamVolumeIndex(int stream, int index) {
503        AudioSystem.setStreamVolumeIndex(stream, (index + 5)/10);
504    }
505
506    private int rescaleIndex(int index, int srcStream, int dstStream) {
507        return (index * mStreamStates[dstStream].getMaxIndex() + mStreamStates[srcStream].getMaxIndex() / 2) / mStreamStates[srcStream].getMaxIndex();
508    }
509
510    ///////////////////////////////////////////////////////////////////////////
511    // IPC methods
512    ///////////////////////////////////////////////////////////////////////////
513
514    /** @see AudioManager#adjustVolume(int, int) */
515    public void adjustVolume(int direction, int flags) {
516        adjustSuggestedStreamVolume(direction, AudioManager.USE_DEFAULT_STREAM_TYPE, flags);
517    }
518
519    /** @see AudioManager#adjustVolume(int, int, int) */
520    public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) {
521
522        int streamType;
523        if ((flags & AudioManager.FLAG_FORCE_STREAM) != 0) {
524            streamType = suggestedStreamType;
525        } else {
526            streamType = getActiveStreamType(suggestedStreamType);
527        }
528
529        // Play sounds on STREAM_RING only and if lock screen is not on.
530        if ((flags & AudioManager.FLAG_PLAY_SOUND) != 0 &&
531                ((STREAM_VOLUME_ALIAS[streamType] != AudioSystem.STREAM_RING)
532                 || (mKeyguardManager != null && mKeyguardManager.isKeyguardLocked()))) {
533            flags &= ~AudioManager.FLAG_PLAY_SOUND;
534        }
535
536        adjustStreamVolume(streamType, direction, flags);
537    }
538
539    /** @see AudioManager#adjustStreamVolume(int, int, int) */
540    public void adjustStreamVolume(int streamType, int direction, int flags) {
541        ensureValidDirection(direction);
542        ensureValidStreamType(streamType);
543
544        // use stream type alias here so that streams with same alias have the same behavior,
545        // including with regard to silent mode control (e.g the use of STREAM_RING below and in
546        // checkForRingerModeChange() in place of STREAM_RING or STREAM_NOTIFICATION)
547        int streamTypeAlias = STREAM_VOLUME_ALIAS[streamType];
548        VolumeStreamState streamState = mStreamStates[streamTypeAlias];
549        final int oldIndex = (streamState.muteCount() != 0) ? streamState.mLastAudibleIndex : streamState.mIndex;
550        boolean adjustVolume = true;
551
552        // If either the client forces allowing ringer modes for this adjustment,
553        // or the stream type is one that is affected by ringer modes
554        if (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) ||
555                streamTypeAlias == AudioSystem.STREAM_RING ||
556                (!mVoiceCapable && streamTypeAlias == AudioSystem.STREAM_MUSIC)) {
557            // do not vibrate if already in vibrate mode
558            if (mRingerMode == AudioManager.RINGER_MODE_VIBRATE) {
559                flags &= ~AudioManager.FLAG_VIBRATE;
560            }
561            // Check if the ringer mode changes with this volume adjustment. If
562            // it does, it will handle adjusting the volume, so we won't below
563            adjustVolume = checkForRingerModeChange(oldIndex, direction, streamTypeAlias);
564        }
565
566        // If stream is muted, adjust last audible index only
567        int index;
568        if (streamState.muteCount() != 0) {
569            if (adjustVolume) {
570                // adjust volume on all stream types sharing the same alias otherwise a query
571                // on last audible index for an alias would not give the correct value
572                int numStreamTypes = AudioSystem.getNumStreamTypes();
573                for (int i = numStreamTypes - 1; i >= 0; i--) {
574                    if (STREAM_VOLUME_ALIAS[i] == streamTypeAlias) {
575                        VolumeStreamState s = mStreamStates[i];
576
577                        s.adjustLastAudibleIndex(direction);
578                        // Post a persist volume msg
579                        sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, i,
580                                SENDMSG_REPLACE, 0, 1, s, PERSIST_DELAY);
581                    }
582                }
583            }
584            index = streamState.mLastAudibleIndex;
585        } else {
586            if (adjustVolume && streamState.adjustIndex(direction)) {
587                // Post message to set system volume (it in turn will post a message
588                // to persist). Do not change volume if stream is muted.
589                sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, streamTypeAlias, SENDMSG_NOOP, 0, 0,
590                        streamState, 0);
591            }
592            index = streamState.mIndex;
593        }
594
595        sendVolumeUpdate(streamType, oldIndex, index, flags);
596    }
597
598    /** @see AudioManager#adjustMasterVolume(int) */
599    public void adjustMasterVolume(int direction, int flags) {
600        ensureValidDirection(direction);
601
602        float volume = AudioSystem.getMasterVolume();
603        Log.d(TAG, "adjustMasterVolume old=" + volume);
604        if (volume >= 0.0) {
605            // get current master volume adjusted to 0 to 100
606            int oldVolume = getMasterVolume();
607            if (direction == AudioManager.ADJUST_RAISE) {
608                volume += MASTER_VOLUME_INCREMENT;
609                if (volume > 1.0f) volume = 1.0f;
610            } else if (direction == AudioManager.ADJUST_LOWER) {
611                volume -= MASTER_VOLUME_INCREMENT;
612                if (volume < 0.0f) volume = 0.0f;
613            }
614            AudioSystem.setMasterVolume(volume);
615            long origCallerIdentityToken = Binder.clearCallingIdentity();
616            Settings.System.putFloat(mContentResolver, Settings.System.VOLUME_MASTER, volume);
617            Binder.restoreCallingIdentity(origCallerIdentityToken);
618            sendMasterVolumeUpdate(flags, oldVolume, getMasterVolume());
619        }
620        Log.d(TAG, "adjustMasterVolume new=" + volume);
621    }
622
623    /** @see AudioManager#setStreamVolume(int, int, int) */
624    public void setStreamVolume(int streamType, int index, int flags) {
625        ensureValidStreamType(streamType);
626        VolumeStreamState streamState = mStreamStates[STREAM_VOLUME_ALIAS[streamType]];
627
628        final int oldIndex = (streamState.muteCount() != 0) ? streamState.mLastAudibleIndex : streamState.mIndex;
629
630        // setting ring or notifications volume to 0 on voice capable devices enters silent mode
631        if (mVoiceCapable && (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) ||
632                (STREAM_VOLUME_ALIAS[streamType] == AudioSystem.STREAM_RING))) {
633            int newRingerMode = mRingerMode;
634            if (index == 0) {
635                newRingerMode = System.getInt(mContentResolver, System.VIBRATE_IN_SILENT, 1) == 1
636                    ? AudioManager.RINGER_MODE_VIBRATE
637                    : AudioManager.RINGER_MODE_SILENT;
638                setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, false, true);
639            } else {
640                newRingerMode = AudioManager.RINGER_MODE_NORMAL;
641            }
642            if (newRingerMode != mRingerMode) {
643                setRingerMode(newRingerMode);
644            }
645        }
646
647        index = rescaleIndex(index * 10, streamType, STREAM_VOLUME_ALIAS[streamType]);
648        setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, false, true);
649
650        index = (streamState.muteCount() != 0) ? streamState.mLastAudibleIndex : streamState.mIndex;
651
652        sendVolumeUpdate(streamType, oldIndex, index, flags);
653    }
654
655    // UI update and Broadcast Intent
656    private void sendVolumeUpdate(int streamType, int oldIndex, int index, int flags) {
657        if (!mVoiceCapable && (streamType == AudioSystem.STREAM_RING)) {
658            streamType = AudioSystem.STREAM_NOTIFICATION;
659        }
660
661        mVolumePanel.postVolumeChanged(streamType, flags);
662
663        oldIndex = (oldIndex + 5) / 10;
664        index = (index + 5) / 10;
665        Intent intent = new Intent(AudioManager.VOLUME_CHANGED_ACTION);
666        intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, streamType);
667        intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, index);
668        intent.putExtra(AudioManager.EXTRA_PREV_VOLUME_STREAM_VALUE, oldIndex);
669        mContext.sendBroadcast(intent);
670    }
671
672    // UI update and Broadcast Intent
673    private void sendMasterVolumeUpdate(int flags, int oldVolume, int newVolume) {
674        mVolumePanel.postMasterVolumeChanged(flags);
675
676        Intent intent = new Intent(AudioManager.MASTER_VOLUME_CHANGED_ACTION);
677        intent.putExtra(AudioManager.EXTRA_PREV_MASTER_VOLUME_VALUE, oldVolume);
678        intent.putExtra(AudioManager.EXTRA_MASTER_VOLUME_VALUE, newVolume);
679        mContext.sendBroadcast(intent);
680    }
681
682    // UI update and Broadcast Intent
683    private void sendMasterMuteUpdate(boolean muted, int flags) {
684        mVolumePanel.postMasterMuteChanged(flags);
685
686        Intent intent = new Intent(AudioManager.MASTER_MUTE_CHANGED_ACTION);
687        intent.putExtra(AudioManager.EXTRA_MASTER_VOLUME_MUTED, muted);
688        long origCallerIdentityToken = Binder.clearCallingIdentity();
689        mContext.sendStickyBroadcast(intent);
690        Binder.restoreCallingIdentity(origCallerIdentityToken);
691    }
692
693    /**
694     * Sets the stream state's index, and posts a message to set system volume.
695     * This will not call out to the UI. Assumes a valid stream type.
696     *
697     * @param streamType Type of the stream
698     * @param index Desired volume index of the stream
699     * @param force If true, set the volume even if the desired volume is same
700     * as the current volume.
701     * @param lastAudible If true, stores new index as last audible one
702     */
703    private void setStreamVolumeInt(int streamType, int index, boolean force, boolean lastAudible) {
704        VolumeStreamState streamState = mStreamStates[streamType];
705
706        // If stream is muted, set last audible index only
707        if (streamState.muteCount() != 0) {
708            // Do not allow last audible index to be 0
709            if (index != 0) {
710                streamState.setLastAudibleIndex(index);
711                // Post a persist volume msg
712                sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamType,
713                        SENDMSG_REPLACE, 0, 1, streamState, PERSIST_DELAY);
714            }
715        } else {
716            if (streamState.setIndex(index, lastAudible) || force) {
717                // Post message to set system volume (it in turn will post a message
718                // to persist).
719                sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, streamType, SENDMSG_NOOP, 0, 0,
720                        streamState, 0);
721            }
722        }
723    }
724
725    /** @see AudioManager#setStreamSolo(int, boolean) */
726    public void setStreamSolo(int streamType, boolean state, IBinder cb) {
727        for (int stream = 0; stream < mStreamStates.length; stream++) {
728            if (!isStreamAffectedByMute(stream) || stream == streamType) continue;
729            // Bring back last audible volume
730            mStreamStates[stream].mute(cb, state);
731         }
732    }
733
734    /** @see AudioManager#setStreamMute(int, boolean) */
735    public void setStreamMute(int streamType, boolean state, IBinder cb) {
736        if (isStreamAffectedByMute(streamType)) {
737            mStreamStates[streamType].mute(cb, state);
738        }
739    }
740
741    /** get stream mute state. */
742    public boolean isStreamMute(int streamType) {
743        return (mStreamStates[streamType].muteCount() != 0);
744    }
745
746    /** @see AudioManager#setMasterMute(boolean, IBinder) */
747    public void setMasterMute(boolean state, IBinder cb) {
748        AudioSystem.setMasterMute(state);
749        sendMasterMuteUpdate(state, AudioManager.FLAG_SHOW_UI);
750    }
751
752    /** get master mute state. */
753    public boolean isMasterMute() {
754        return AudioSystem.getMasterMute();
755    }
756
757    /** @see AudioManager#getStreamVolume(int) */
758    public int getStreamVolume(int streamType) {
759        ensureValidStreamType(streamType);
760        return (mStreamStates[streamType].mIndex + 5) / 10;
761    }
762
763    public int getMasterVolume() {
764        if (isMasterMute()) return 0;
765        return getLastAudibleMasterVolume();
766    }
767
768    public void setMasterVolume(int volume, int flags) {
769        AudioSystem.setMasterVolume((float)volume / MAX_MASTER_VOLUME);
770    }
771
772    /** @see AudioManager#getStreamMaxVolume(int) */
773    public int getStreamMaxVolume(int streamType) {
774        ensureValidStreamType(streamType);
775        return (mStreamStates[streamType].getMaxIndex() + 5) / 10;
776    }
777
778    public int getMasterMaxVolume() {
779        return MAX_MASTER_VOLUME;
780    }
781
782    /** Get last audible volume before stream was muted. */
783    public int getLastAudibleStreamVolume(int streamType) {
784        ensureValidStreamType(streamType);
785        return (mStreamStates[streamType].mLastAudibleIndex + 5) / 10;
786    }
787
788    /** Get last audible master volume before it was muted. */
789    public int getLastAudibleMasterVolume() {
790        return Math.round(AudioSystem.getMasterVolume() * MAX_MASTER_VOLUME);
791    }
792
793    /** @see AudioManager#getRingerMode() */
794    public int getRingerMode() {
795        return mRingerMode;
796    }
797
798    /** @see AudioManager#setRingerMode(int) */
799    public void setRingerMode(int ringerMode) {
800        synchronized (mSettingsLock) {
801            if (ringerMode != mRingerMode) {
802                setRingerModeInt(ringerMode, true);
803                // Send sticky broadcast
804                broadcastRingerMode();
805            }
806        }
807    }
808
809    private void setRingerModeInt(int ringerMode, boolean persist) {
810        mRingerMode = ringerMode;
811
812        // Mute stream if not previously muted by ringer mode and ringer mode
813        // is not RINGER_MODE_NORMAL and stream is affected by ringer mode.
814        // Unmute stream if previously muted by ringer mode and ringer mode
815        // is RINGER_MODE_NORMAL or stream is not affected by ringer mode.
816        int numStreamTypes = AudioSystem.getNumStreamTypes();
817        for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
818            if (isStreamMutedByRingerMode(streamType)) {
819                if (!isStreamAffectedByRingerMode(streamType) ||
820                    mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
821                    // ring and notifications volume should never be 0 when not silenced
822                    // on voice capable devices
823                    if (mVoiceCapable &&
824                            STREAM_VOLUME_ALIAS[streamType] == AudioSystem.STREAM_RING &&
825                            mStreamStates[streamType].mLastAudibleIndex == 0) {
826                        mStreamStates[streamType].mLastAudibleIndex = 10;
827                    }
828                    mStreamStates[streamType].mute(null, false);
829                    mRingerModeMutedStreams &= ~(1 << streamType);
830                }
831            } else {
832                if (isStreamAffectedByRingerMode(streamType) &&
833                    mRingerMode != AudioManager.RINGER_MODE_NORMAL) {
834                   mStreamStates[streamType].mute(null, true);
835                   mRingerModeMutedStreams |= (1 << streamType);
836               }
837            }
838        }
839
840        // Post a persist ringer mode msg
841        if (persist) {
842            sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE, SHARED_MSG,
843                    SENDMSG_REPLACE, 0, 0, null, PERSIST_DELAY);
844        }
845    }
846
847    /** @see AudioManager#shouldVibrate(int) */
848    public boolean shouldVibrate(int vibrateType) {
849
850        switch (getVibrateSetting(vibrateType)) {
851
852            case AudioManager.VIBRATE_SETTING_ON:
853                return mRingerMode != AudioManager.RINGER_MODE_SILENT;
854
855            case AudioManager.VIBRATE_SETTING_ONLY_SILENT:
856                return mRingerMode == AudioManager.RINGER_MODE_VIBRATE;
857
858            case AudioManager.VIBRATE_SETTING_OFF:
859                // return false, even for incoming calls
860                return false;
861
862            default:
863                return false;
864        }
865    }
866
867    /** @see AudioManager#getVibrateSetting(int) */
868    public int getVibrateSetting(int vibrateType) {
869        return (mVibrateSetting >> (vibrateType * 2)) & 3;
870    }
871
872    /** @see AudioManager#setVibrateSetting(int, int) */
873    public void setVibrateSetting(int vibrateType, int vibrateSetting) {
874
875        mVibrateSetting = getValueForVibrateSetting(mVibrateSetting, vibrateType, vibrateSetting);
876
877        // Broadcast change
878        broadcastVibrateSetting(vibrateType);
879
880        // Post message to set ringer mode (it in turn will post a message
881        // to persist)
882        sendMsg(mAudioHandler, MSG_PERSIST_VIBRATE_SETTING, SHARED_MSG, SENDMSG_NOOP, 0, 0,
883                null, 0);
884    }
885
886    /**
887     * @see #setVibrateSetting(int, int)
888     */
889    public static int getValueForVibrateSetting(int existingValue, int vibrateType,
890            int vibrateSetting) {
891
892        // First clear the existing setting. Each vibrate type has two bits in
893        // the value. Note '3' is '11' in binary.
894        existingValue &= ~(3 << (vibrateType * 2));
895
896        // Set into the old value
897        existingValue |= (vibrateSetting & 3) << (vibrateType * 2);
898
899        return existingValue;
900    }
901
902    private class SetModeDeathHandler implements IBinder.DeathRecipient {
903        private IBinder mCb; // To be notified of client's death
904        private int mPid;
905        private int mMode = AudioSystem.MODE_NORMAL; // Current mode set by this client
906
907        SetModeDeathHandler(IBinder cb, int pid) {
908            mCb = cb;
909            mPid = pid;
910        }
911
912        public void binderDied() {
913            int newModeOwnerPid = 0;
914            synchronized(mSetModeDeathHandlers) {
915                Log.w(TAG, "setMode() client died");
916                int index = mSetModeDeathHandlers.indexOf(this);
917                if (index < 0) {
918                    Log.w(TAG, "unregistered setMode() client died");
919                } else {
920                    newModeOwnerPid = setModeInt(AudioSystem.MODE_NORMAL, mCb, mPid);
921                }
922            }
923            // when entering RINGTONE, IN_CALL or IN_COMMUNICATION mode, clear all
924            // SCO connections not started by the application changing the mode
925            if (newModeOwnerPid != 0) {
926                 disconnectBluetoothSco(newModeOwnerPid);
927            }
928        }
929
930        public int getPid() {
931            return mPid;
932        }
933
934        public void setMode(int mode) {
935            mMode = mode;
936        }
937
938        public int getMode() {
939            return mMode;
940        }
941
942        public IBinder getBinder() {
943            return mCb;
944        }
945    }
946
947    /** @see AudioManager#setMode(int) */
948    public void setMode(int mode, IBinder cb) {
949        if (!checkAudioSettingsPermission("setMode()")) {
950            return;
951        }
952
953        if (mode < AudioSystem.MODE_CURRENT || mode >= AudioSystem.NUM_MODES) {
954            return;
955        }
956
957        int newModeOwnerPid = 0;
958        synchronized(mSetModeDeathHandlers) {
959            if (mode == AudioSystem.MODE_CURRENT) {
960                mode = mMode;
961            }
962            newModeOwnerPid = setModeInt(mode, cb, Binder.getCallingPid());
963        }
964        // when entering RINGTONE, IN_CALL or IN_COMMUNICATION mode, clear all
965        // SCO connections not started by the application changing the mode
966        if (newModeOwnerPid != 0) {
967             disconnectBluetoothSco(newModeOwnerPid);
968        }
969    }
970
971    // must be called synchronized on mSetModeDeathHandlers
972    // setModeInt() returns a valid PID if the audio mode was successfully set to
973    // any mode other than NORMAL.
974    int setModeInt(int mode, IBinder cb, int pid) {
975        int newModeOwnerPid = 0;
976        if (cb == null) {
977            Log.e(TAG, "setModeInt() called with null binder");
978            return newModeOwnerPid;
979        }
980
981        SetModeDeathHandler hdlr = null;
982        Iterator iter = mSetModeDeathHandlers.iterator();
983        while (iter.hasNext()) {
984            SetModeDeathHandler h = (SetModeDeathHandler)iter.next();
985            if (h.getPid() == pid) {
986                hdlr = h;
987                // Remove from client list so that it is re-inserted at top of list
988                iter.remove();
989                hdlr.getBinder().unlinkToDeath(hdlr, 0);
990                break;
991            }
992        }
993        int status = AudioSystem.AUDIO_STATUS_OK;
994        do {
995            if (mode == AudioSystem.MODE_NORMAL) {
996                // get new mode from client at top the list if any
997                if (!mSetModeDeathHandlers.isEmpty()) {
998                    hdlr = mSetModeDeathHandlers.get(0);
999                    cb = hdlr.getBinder();
1000                    mode = hdlr.getMode();
1001                }
1002            } else {
1003                if (hdlr == null) {
1004                    hdlr = new SetModeDeathHandler(cb, pid);
1005                }
1006                // Register for client death notification
1007                try {
1008                    cb.linkToDeath(hdlr, 0);
1009                } catch (RemoteException e) {
1010                    // Client has died!
1011                    Log.w(TAG, "setMode() could not link to "+cb+" binder death");
1012                }
1013
1014                // Last client to call setMode() is always at top of client list
1015                // as required by SetModeDeathHandler.binderDied()
1016                mSetModeDeathHandlers.add(0, hdlr);
1017                hdlr.setMode(mode);
1018            }
1019
1020            if (mode != mMode) {
1021                status = AudioSystem.setPhoneState(mode);
1022                if (status == AudioSystem.AUDIO_STATUS_OK) {
1023                    // automatically handle audio focus for mode changes
1024                    handleFocusForCalls(mMode, mode, cb);
1025                    mMode = mode;
1026                } else {
1027                    if (hdlr != null) {
1028                        mSetModeDeathHandlers.remove(hdlr);
1029                        cb.unlinkToDeath(hdlr, 0);
1030                    }
1031                    // force reading new top of mSetModeDeathHandlers stack
1032                    mode = AudioSystem.MODE_NORMAL;
1033                }
1034            } else {
1035                status = AudioSystem.AUDIO_STATUS_OK;
1036            }
1037        } while (status != AudioSystem.AUDIO_STATUS_OK && !mSetModeDeathHandlers.isEmpty());
1038
1039        if (status == AudioSystem.AUDIO_STATUS_OK) {
1040            if (mode != AudioSystem.MODE_NORMAL) {
1041                if (mSetModeDeathHandlers.isEmpty()) {
1042                    Log.e(TAG, "setMode() different from MODE_NORMAL with empty mode client stack");
1043                } else {
1044                    newModeOwnerPid = mSetModeDeathHandlers.get(0).getPid();
1045                }
1046            }
1047            int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
1048            int index = mStreamStates[STREAM_VOLUME_ALIAS[streamType]].mIndex;
1049            setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, true, false);
1050        }
1051        return newModeOwnerPid;
1052    }
1053
1054    /** pre-condition: oldMode != newMode */
1055    private void handleFocusForCalls(int oldMode, int newMode, IBinder cb) {
1056        // if ringing
1057        if (newMode == AudioSystem.MODE_RINGTONE) {
1058            // if not ringing silently
1059            int ringVolume = AudioService.this.getStreamVolume(AudioManager.STREAM_RING);
1060            if (ringVolume > 0) {
1061                // request audio focus for the communication focus entry
1062                requestAudioFocus(AudioManager.STREAM_RING,
1063                        AudioManager.AUDIOFOCUS_GAIN_TRANSIENT, cb,
1064                        null /* IAudioFocusDispatcher allowed to be null only for this clientId */,
1065                        IN_VOICE_COMM_FOCUS_ID /*clientId*/,
1066                        "system");
1067
1068            }
1069        }
1070        // if entering call
1071        else if ((newMode == AudioSystem.MODE_IN_CALL)
1072                || (newMode == AudioSystem.MODE_IN_COMMUNICATION)) {
1073            // request audio focus for the communication focus entry
1074            // (it's ok if focus was already requested during ringing)
1075            requestAudioFocus(AudioManager.STREAM_RING,
1076                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT, cb,
1077                    null /* IAudioFocusDispatcher allowed to be null only for this clientId */,
1078                    IN_VOICE_COMM_FOCUS_ID /*clientId*/,
1079                    "system");
1080        }
1081        // if exiting call
1082        else if (newMode == AudioSystem.MODE_NORMAL) {
1083            // abandon audio focus for communication focus entry
1084            abandonAudioFocus(null, IN_VOICE_COMM_FOCUS_ID);
1085        }
1086    }
1087
1088    /** @see AudioManager#getMode() */
1089    public int getMode() {
1090        return mMode;
1091    }
1092
1093    /** @see AudioManager#playSoundEffect(int) */
1094    public void playSoundEffect(int effectType) {
1095        sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP,
1096                effectType, -1, null, 0);
1097    }
1098
1099    /** @see AudioManager#playSoundEffect(int, float) */
1100    public void playSoundEffectVolume(int effectType, float volume) {
1101        loadSoundEffects();
1102        sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP,
1103                effectType, (int) (volume * 1000), null, 0);
1104    }
1105
1106    /**
1107     * Loads samples into the soundpool.
1108     * This method must be called at when sound effects are enabled
1109     */
1110    public boolean loadSoundEffects() {
1111        int status;
1112
1113        synchronized (mSoundEffectsLock) {
1114            if (!mBootCompleted) {
1115                Log.w(TAG, "loadSoundEffects() called before boot complete");
1116                return false;
1117            }
1118
1119            if (mSoundPool != null) {
1120                return true;
1121            }
1122            mSoundPool = new SoundPool(NUM_SOUNDPOOL_CHANNELS, AudioSystem.STREAM_SYSTEM, 0);
1123            if (mSoundPool == null) {
1124                Log.w(TAG, "loadSoundEffects() could not allocate sound pool");
1125                return false;
1126            }
1127
1128            try {
1129                mSoundPoolCallBack = null;
1130                mSoundPoolListenerThread = new SoundPoolListenerThread();
1131                mSoundPoolListenerThread.start();
1132                // Wait for mSoundPoolCallBack to be set by the other thread
1133                mSoundEffectsLock.wait();
1134            } catch (InterruptedException e) {
1135                Log.w(TAG, "Interrupted while waiting sound pool listener thread.");
1136            }
1137
1138            if (mSoundPoolCallBack == null) {
1139                Log.w(TAG, "loadSoundEffects() could not create SoundPool listener or thread");
1140                if (mSoundPoolLooper != null) {
1141                    mSoundPoolLooper.quit();
1142                    mSoundPoolLooper = null;
1143                }
1144                mSoundPoolListenerThread = null;
1145                mSoundPool.release();
1146                mSoundPool = null;
1147                return false;
1148            }
1149            /*
1150             * poolId table: The value -1 in this table indicates that corresponding
1151             * file (same index in SOUND_EFFECT_FILES[] has not been loaded.
1152             * Once loaded, the value in poolId is the sample ID and the same
1153             * sample can be reused for another effect using the same file.
1154             */
1155            int[] poolId = new int[SOUND_EFFECT_FILES.length];
1156            for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) {
1157                poolId[fileIdx] = -1;
1158            }
1159            /*
1160             * Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded.
1161             * If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0:
1162             * this indicates we have a valid sample loaded for this effect.
1163             */
1164
1165            int lastSample = 0;
1166            for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
1167                // Do not load sample if this effect uses the MediaPlayer
1168                if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) {
1169                    continue;
1170                }
1171                if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) {
1172                    String filePath = Environment.getRootDirectory()
1173                            + SOUND_EFFECTS_PATH
1174                            + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effect][0]];
1175                    int sampleId = mSoundPool.load(filePath, 0);
1176                    if (sampleId <= 0) {
1177                        Log.w(TAG, "Soundpool could not load file: "+filePath);
1178                    } else {
1179                        SOUND_EFFECT_FILES_MAP[effect][1] = sampleId;
1180                        poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId;
1181                        lastSample = sampleId;
1182                    }
1183                } else {
1184                    SOUND_EFFECT_FILES_MAP[effect][1] = poolId[SOUND_EFFECT_FILES_MAP[effect][0]];
1185                }
1186            }
1187            // wait for all samples to be loaded
1188            if (lastSample != 0) {
1189                mSoundPoolCallBack.setLastSample(lastSample);
1190
1191                try {
1192                    mSoundEffectsLock.wait();
1193                    status = mSoundPoolCallBack.status();
1194                } catch (java.lang.InterruptedException e) {
1195                    Log.w(TAG, "Interrupted while waiting sound pool callback.");
1196                    status = -1;
1197                }
1198            } else {
1199                status = -1;
1200            }
1201
1202            if (mSoundPoolLooper != null) {
1203                mSoundPoolLooper.quit();
1204                mSoundPoolLooper = null;
1205            }
1206            mSoundPoolListenerThread = null;
1207            if (status != 0) {
1208                Log.w(TAG,
1209                        "loadSoundEffects(), Error "
1210                                + ((lastSample != 0) ? mSoundPoolCallBack.status() : -1)
1211                                + " while loading samples");
1212                for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
1213                    if (SOUND_EFFECT_FILES_MAP[effect][1] > 0) {
1214                        SOUND_EFFECT_FILES_MAP[effect][1] = -1;
1215                    }
1216                }
1217
1218                mSoundPool.release();
1219                mSoundPool = null;
1220            }
1221        }
1222        return (status == 0);
1223    }
1224
1225    /**
1226     *  Unloads samples from the sound pool.
1227     *  This method can be called to free some memory when
1228     *  sound effects are disabled.
1229     */
1230    public void unloadSoundEffects() {
1231        synchronized (mSoundEffectsLock) {
1232            if (mSoundPool == null) {
1233                return;
1234            }
1235
1236            mAudioHandler.removeMessages(MSG_LOAD_SOUND_EFFECTS);
1237            mAudioHandler.removeMessages(MSG_PLAY_SOUND_EFFECT);
1238
1239            int[] poolId = new int[SOUND_EFFECT_FILES.length];
1240            for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) {
1241                poolId[fileIdx] = 0;
1242            }
1243
1244            for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
1245                if (SOUND_EFFECT_FILES_MAP[effect][1] <= 0) {
1246                    continue;
1247                }
1248                if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == 0) {
1249                    mSoundPool.unload(SOUND_EFFECT_FILES_MAP[effect][1]);
1250                    SOUND_EFFECT_FILES_MAP[effect][1] = -1;
1251                    poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1;
1252                }
1253            }
1254            mSoundPool.release();
1255            mSoundPool = null;
1256        }
1257    }
1258
1259    class SoundPoolListenerThread extends Thread {
1260        public SoundPoolListenerThread() {
1261            super("SoundPoolListenerThread");
1262        }
1263
1264        @Override
1265        public void run() {
1266
1267            Looper.prepare();
1268            mSoundPoolLooper = Looper.myLooper();
1269
1270            synchronized (mSoundEffectsLock) {
1271                if (mSoundPool != null) {
1272                    mSoundPoolCallBack = new SoundPoolCallback();
1273                    mSoundPool.setOnLoadCompleteListener(mSoundPoolCallBack);
1274                }
1275                mSoundEffectsLock.notify();
1276            }
1277            Looper.loop();
1278        }
1279    }
1280
1281    private final class SoundPoolCallback implements
1282            android.media.SoundPool.OnLoadCompleteListener {
1283
1284        int mStatus;
1285        int mLastSample;
1286
1287        public int status() {
1288            return mStatus;
1289        }
1290
1291        public void setLastSample(int sample) {
1292            mLastSample = sample;
1293        }
1294
1295        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
1296            synchronized (mSoundEffectsLock) {
1297                if (status != 0) {
1298                    mStatus = status;
1299                }
1300                if (sampleId == mLastSample) {
1301                    mSoundEffectsLock.notify();
1302                }
1303            }
1304        }
1305    }
1306
1307    /** @see AudioManager#reloadAudioSettings() */
1308    public void reloadAudioSettings() {
1309        // restore ringer mode, ringer mode affected streams, mute affected streams and vibrate settings
1310        readPersistedSettings();
1311
1312        // restore volume settings
1313        int numStreamTypes = AudioSystem.getNumStreamTypes();
1314        for (int streamType = 0; streamType < numStreamTypes; streamType++) {
1315            VolumeStreamState streamState = mStreamStates[streamType];
1316
1317            String settingName = System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[streamType]];
1318            String lastAudibleSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE;
1319            int index = Settings.System.getInt(mContentResolver,
1320                                           settingName,
1321                                           AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1322            if (STREAM_VOLUME_ALIAS[streamType] != streamType) {
1323                index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType);
1324            } else {
1325                index *= 10;
1326            }
1327            streamState.mIndex = streamState.getValidIndex(index);
1328
1329            index = (index + 5) / 10;
1330            index = Settings.System.getInt(mContentResolver,
1331                                            lastAudibleSettingName,
1332                                            (index > 0) ? index : AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1333            if (STREAM_VOLUME_ALIAS[streamType] != streamType) {
1334                index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType);
1335            } else {
1336                index *= 10;
1337            }
1338            streamState.mLastAudibleIndex = streamState.getValidIndex(index);
1339
1340            // unmute stream that was muted but is not affect by mute anymore
1341            if (streamState.muteCount() != 0 && !isStreamAffectedByMute(streamType)) {
1342                int size = streamState.mDeathHandlers.size();
1343                for (int i = 0; i < size; i++) {
1344                    streamState.mDeathHandlers.get(i).mMuteCount = 1;
1345                    streamState.mDeathHandlers.get(i).mute(false);
1346                }
1347            }
1348            // apply stream volume
1349            if (streamState.muteCount() == 0) {
1350                setStreamVolumeIndex(streamType, streamState.mIndex);
1351            }
1352        }
1353
1354        // apply new ringer mode
1355        setRingerModeInt(getRingerMode(), false);
1356    }
1357
1358    /** @see AudioManager#setSpeakerphoneOn() */
1359    public void setSpeakerphoneOn(boolean on){
1360        if (!checkAudioSettingsPermission("setSpeakerphoneOn()")) {
1361            return;
1362        }
1363        mForcedUseForComm = on ? AudioSystem.FORCE_SPEAKER : AudioSystem.FORCE_NONE;
1364
1365        sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SHARED_MSG, SENDMSG_QUEUE,
1366                AudioSystem.FOR_COMMUNICATION, mForcedUseForComm, null, 0);
1367    }
1368
1369    /** @see AudioManager#isSpeakerphoneOn() */
1370    public boolean isSpeakerphoneOn() {
1371        return (mForcedUseForComm == AudioSystem.FORCE_SPEAKER);
1372    }
1373
1374    /** @see AudioManager#setBluetoothScoOn() */
1375    public void setBluetoothScoOn(boolean on){
1376        if (!checkAudioSettingsPermission("setBluetoothScoOn()")) {
1377            return;
1378        }
1379        mForcedUseForComm = on ? AudioSystem.FORCE_BT_SCO : AudioSystem.FORCE_NONE;
1380
1381        sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SHARED_MSG, SENDMSG_QUEUE,
1382                AudioSystem.FOR_COMMUNICATION, mForcedUseForComm, null, 0);
1383        sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SHARED_MSG, SENDMSG_QUEUE,
1384                AudioSystem.FOR_RECORD, mForcedUseForComm, null, 0);
1385    }
1386
1387    /** @see AudioManager#isBluetoothScoOn() */
1388    public boolean isBluetoothScoOn() {
1389        return (mForcedUseForComm == AudioSystem.FORCE_BT_SCO);
1390    }
1391
1392    /** @see AudioManager#startBluetoothSco() */
1393    public void startBluetoothSco(IBinder cb){
1394        if (!checkAudioSettingsPermission("startBluetoothSco()") ||
1395                !mBootCompleted) {
1396            return;
1397        }
1398        ScoClient client = getScoClient(cb, true);
1399        client.incCount();
1400    }
1401
1402    /** @see AudioManager#stopBluetoothSco() */
1403    public void stopBluetoothSco(IBinder cb){
1404        if (!checkAudioSettingsPermission("stopBluetoothSco()") ||
1405                !mBootCompleted) {
1406            return;
1407        }
1408        ScoClient client = getScoClient(cb, false);
1409        if (client != null) {
1410            client.decCount();
1411        }
1412    }
1413
1414    private class ScoClient implements IBinder.DeathRecipient {
1415        private IBinder mCb; // To be notified of client's death
1416        private int mCreatorPid;
1417        private int mStartcount; // number of SCO connections started by this client
1418
1419        ScoClient(IBinder cb) {
1420            mCb = cb;
1421            mCreatorPid = Binder.getCallingPid();
1422            mStartcount = 0;
1423        }
1424
1425        public void binderDied() {
1426            synchronized(mScoClients) {
1427                Log.w(TAG, "SCO client died");
1428                int index = mScoClients.indexOf(this);
1429                if (index < 0) {
1430                    Log.w(TAG, "unregistered SCO client died");
1431                } else {
1432                    clearCount(true);
1433                    mScoClients.remove(this);
1434                }
1435            }
1436        }
1437
1438        public void incCount() {
1439            synchronized(mScoClients) {
1440                requestScoState(BluetoothHeadset.STATE_AUDIO_CONNECTED);
1441                if (mStartcount == 0) {
1442                    try {
1443                        mCb.linkToDeath(this, 0);
1444                    } catch (RemoteException e) {
1445                        // client has already died!
1446                        Log.w(TAG, "ScoClient  incCount() could not link to "+mCb+" binder death");
1447                    }
1448                }
1449                mStartcount++;
1450            }
1451        }
1452
1453        public void decCount() {
1454            synchronized(mScoClients) {
1455                if (mStartcount == 0) {
1456                    Log.w(TAG, "ScoClient.decCount() already 0");
1457                } else {
1458                    mStartcount--;
1459                    if (mStartcount == 0) {
1460                        try {
1461                            mCb.unlinkToDeath(this, 0);
1462                        } catch (NoSuchElementException e) {
1463                            Log.w(TAG, "decCount() going to 0 but not registered to binder");
1464                        }
1465                    }
1466                    requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
1467                }
1468            }
1469        }
1470
1471        public void clearCount(boolean stopSco) {
1472            synchronized(mScoClients) {
1473                if (mStartcount != 0) {
1474                    try {
1475                        mCb.unlinkToDeath(this, 0);
1476                    } catch (NoSuchElementException e) {
1477                        Log.w(TAG, "clearCount() mStartcount: "+mStartcount+" != 0 but not registered to binder");
1478                    }
1479                }
1480                mStartcount = 0;
1481                if (stopSco) {
1482                    requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
1483                }
1484            }
1485        }
1486
1487        public int getCount() {
1488            return mStartcount;
1489        }
1490
1491        public IBinder getBinder() {
1492            return mCb;
1493        }
1494
1495        public int getPid() {
1496            return mCreatorPid;
1497        }
1498
1499        public int totalCount() {
1500            synchronized(mScoClients) {
1501                int count = 0;
1502                int size = mScoClients.size();
1503                for (int i = 0; i < size; i++) {
1504                    count += mScoClients.get(i).getCount();
1505                }
1506                return count;
1507            }
1508        }
1509
1510        private void requestScoState(int state) {
1511            checkScoAudioState();
1512            if (totalCount() == 0) {
1513                if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED) {
1514                    // Make sure that the state transitions to CONNECTING even if we cannot initiate
1515                    // the connection.
1516                    broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTING);
1517                    // Accept SCO audio activation only in NORMAL audio mode or if the mode is
1518                    // currently controlled by the same client process.
1519                    synchronized(mSetModeDeathHandlers) {
1520                        if ((mSetModeDeathHandlers.isEmpty() ||
1521                                mSetModeDeathHandlers.get(0).getPid() == mCreatorPid) &&
1522                                (mScoAudioState == SCO_STATE_INACTIVE ||
1523                                 mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) {
1524                            if (mScoAudioState == SCO_STATE_INACTIVE) {
1525                                if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null) {
1526                                    if (mBluetoothHeadset.startScoUsingVirtualVoiceCall(
1527                                            mBluetoothHeadsetDevice)) {
1528                                        mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
1529                                    } else {
1530                                        broadcastScoConnectionState(
1531                                                AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
1532                                    }
1533                                } else if (getBluetoothHeadset()) {
1534                                    mScoAudioState = SCO_STATE_ACTIVATE_REQ;
1535                                }
1536                            } else {
1537                                mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
1538                                broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTED);
1539                            }
1540                        } else {
1541                            broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
1542                        }
1543                    }
1544                } else if (state == BluetoothHeadset.STATE_AUDIO_DISCONNECTED &&
1545                              (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL ||
1546                               mScoAudioState == SCO_STATE_ACTIVATE_REQ)) {
1547                    if (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL) {
1548                        if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null) {
1549                            if (!mBluetoothHeadset.stopScoUsingVirtualVoiceCall(
1550                                    mBluetoothHeadsetDevice)) {
1551                                mScoAudioState = SCO_STATE_INACTIVE;
1552                                broadcastScoConnectionState(
1553                                        AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
1554                            }
1555                        } else if (getBluetoothHeadset()) {
1556                            mScoAudioState = SCO_STATE_DEACTIVATE_REQ;
1557                        }
1558                    } else {
1559                        mScoAudioState = SCO_STATE_INACTIVE;
1560                        broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
1561                    }
1562                }
1563            }
1564        }
1565    }
1566
1567    private void checkScoAudioState() {
1568        if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null &&
1569                mScoAudioState == SCO_STATE_INACTIVE &&
1570                mBluetoothHeadset.getAudioState(mBluetoothHeadsetDevice)
1571                != BluetoothHeadset.STATE_AUDIO_DISCONNECTED) {
1572            mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
1573        }
1574    }
1575
1576    private ScoClient getScoClient(IBinder cb, boolean create) {
1577        synchronized(mScoClients) {
1578            ScoClient client = null;
1579            int size = mScoClients.size();
1580            for (int i = 0; i < size; i++) {
1581                client = mScoClients.get(i);
1582                if (client.getBinder() == cb)
1583                    return client;
1584            }
1585            if (create) {
1586                client = new ScoClient(cb);
1587                mScoClients.add(client);
1588            }
1589            return client;
1590        }
1591    }
1592
1593    public void clearAllScoClients(int exceptPid, boolean stopSco) {
1594        synchronized(mScoClients) {
1595            ScoClient savedClient = null;
1596            int size = mScoClients.size();
1597            for (int i = 0; i < size; i++) {
1598                ScoClient cl = mScoClients.get(i);
1599                if (cl.getPid() != exceptPid) {
1600                    cl.clearCount(stopSco);
1601                } else {
1602                    savedClient = cl;
1603                }
1604            }
1605            mScoClients.clear();
1606            if (savedClient != null) {
1607                mScoClients.add(savedClient);
1608            }
1609        }
1610    }
1611
1612    private boolean getBluetoothHeadset() {
1613        boolean result = false;
1614        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
1615        if (adapter != null) {
1616            result = adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
1617                                    BluetoothProfile.HEADSET);
1618        }
1619        // If we could not get a bluetooth headset proxy, send a failure message
1620        // without delay to reset the SCO audio state and clear SCO clients.
1621        // If we could get a proxy, send a delayed failure message that will reset our state
1622        // in case we don't receive onServiceConnected().
1623        sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED, 0,
1624                SENDMSG_REPLACE, 0, 0, null, result ? BT_HEADSET_CNCT_TIMEOUT_MS : 0);
1625        return result;
1626    }
1627
1628    private void disconnectBluetoothSco(int exceptPid) {
1629        synchronized(mScoClients) {
1630            checkScoAudioState();
1631            if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL ||
1632                    mScoAudioState == SCO_STATE_DEACTIVATE_EXT_REQ) {
1633                if (mBluetoothHeadsetDevice != null) {
1634                    if (mBluetoothHeadset != null) {
1635                        if (!mBluetoothHeadset.stopVoiceRecognition(
1636                                mBluetoothHeadsetDevice)) {
1637                            sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED, 0,
1638                                    SENDMSG_REPLACE, 0, 0, null, 0);
1639                        }
1640                    } else if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL &&
1641                            getBluetoothHeadset()) {
1642                        mScoAudioState = SCO_STATE_DEACTIVATE_EXT_REQ;
1643                    }
1644                }
1645            } else {
1646                clearAllScoClients(exceptPid, true);
1647            }
1648        }
1649    }
1650
1651    private void resetBluetoothSco() {
1652        synchronized(mScoClients) {
1653            clearAllScoClients(0, false);
1654            mScoAudioState = SCO_STATE_INACTIVE;
1655            broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
1656        }
1657    }
1658
1659    private void broadcastScoConnectionState(int state) {
1660        if (state != mScoConnectionState) {
1661            Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
1662            newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, state);
1663            newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_PREVIOUS_STATE,
1664                    mScoConnectionState);
1665            mContext.sendStickyBroadcast(newIntent);
1666            mScoConnectionState = state;
1667        }
1668    }
1669
1670    private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
1671        new BluetoothProfile.ServiceListener() {
1672        public void onServiceConnected(int profile, BluetoothProfile proxy) {
1673            BluetoothDevice btDevice;
1674            List<BluetoothDevice> deviceList;
1675            switch(profile) {
1676            case BluetoothProfile.A2DP:
1677                BluetoothA2dp a2dp = (BluetoothA2dp) proxy;
1678                deviceList = a2dp.getConnectedDevices();
1679                if (deviceList.size() > 0) {
1680                    btDevice = deviceList.get(0);
1681                    handleA2dpConnectionStateChange(btDevice, a2dp.getConnectionState(btDevice));
1682                }
1683                break;
1684
1685            case BluetoothProfile.HEADSET:
1686                synchronized (mScoClients) {
1687                    // Discard timeout message
1688                    mAudioHandler.removeMessages(MSG_BT_HEADSET_CNCT_FAILED);
1689                    mBluetoothHeadset = (BluetoothHeadset) proxy;
1690                    deviceList = mBluetoothHeadset.getConnectedDevices();
1691                    if (deviceList.size() > 0) {
1692                        mBluetoothHeadsetDevice = deviceList.get(0);
1693                    } else {
1694                        mBluetoothHeadsetDevice = null;
1695                    }
1696                    // Refresh SCO audio state
1697                    checkScoAudioState();
1698                    // Continue pending action if any
1699                    if (mScoAudioState == SCO_STATE_ACTIVATE_REQ ||
1700                            mScoAudioState == SCO_STATE_DEACTIVATE_REQ ||
1701                            mScoAudioState == SCO_STATE_DEACTIVATE_EXT_REQ) {
1702                        boolean status = false;
1703                        if (mBluetoothHeadsetDevice != null) {
1704                            switch (mScoAudioState) {
1705                            case SCO_STATE_ACTIVATE_REQ:
1706                                mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
1707                                status = mBluetoothHeadset.startScoUsingVirtualVoiceCall(
1708                                        mBluetoothHeadsetDevice);
1709                                break;
1710                            case SCO_STATE_DEACTIVATE_REQ:
1711                                status = mBluetoothHeadset.stopScoUsingVirtualVoiceCall(
1712                                        mBluetoothHeadsetDevice);
1713                                break;
1714                            case SCO_STATE_DEACTIVATE_EXT_REQ:
1715                                status = mBluetoothHeadset.stopVoiceRecognition(
1716                                        mBluetoothHeadsetDevice);
1717                            }
1718                        }
1719                        if (!status) {
1720                            sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED, 0,
1721                                    SENDMSG_REPLACE, 0, 0, null, 0);
1722                        }
1723                    }
1724                }
1725                break;
1726
1727            default:
1728                break;
1729            }
1730        }
1731        public void onServiceDisconnected(int profile) {
1732            switch(profile) {
1733            case BluetoothProfile.A2DP:
1734                synchronized (mConnectedDevices) {
1735                    if (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP)) {
1736                        makeA2dpDeviceUnavailableNow(
1737                                mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP));
1738                    }
1739                }
1740                break;
1741
1742            case BluetoothProfile.HEADSET:
1743                synchronized (mScoClients) {
1744                    mBluetoothHeadset = null;
1745                }
1746                break;
1747
1748            default:
1749                break;
1750            }
1751        }
1752    };
1753
1754    ///////////////////////////////////////////////////////////////////////////
1755    // Internal methods
1756    ///////////////////////////////////////////////////////////////////////////
1757
1758    /**
1759     * Checks if the adjustment should change ringer mode instead of just
1760     * adjusting volume. If so, this will set the proper ringer mode and volume
1761     * indices on the stream states.
1762     */
1763    private boolean checkForRingerModeChange(int oldIndex, int direction, int streamType) {
1764        boolean adjustVolumeIndex = true;
1765        int newRingerMode = mRingerMode;
1766        int uiIndex = (oldIndex + 5) / 10;
1767        boolean vibeInSilent = System.getInt(mContentResolver, System.VIBRATE_IN_SILENT, 1) == 1;
1768
1769        if (mRingerMode == RINGER_MODE_NORMAL) {
1770            if ((direction == AudioManager.ADJUST_LOWER) && (uiIndex <= 1)) {
1771                // enter silent mode if current index is the last audible one and not repeating a
1772                // volume key down
1773                if (vibeInSilent || mPrevVolDirection != AudioManager.ADJUST_LOWER) {
1774                    // "silent mode", but which one?
1775                    newRingerMode = vibeInSilent ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT;
1776                }
1777                if (uiIndex == 0 ||
1778                        (!vibeInSilent &&
1779                         mPrevVolDirection == AudioManager.ADJUST_LOWER &&
1780                         mVoiceCapable && streamType == AudioSystem.STREAM_RING)) {
1781                    adjustVolumeIndex = false;
1782                }
1783            }
1784        } else if (mRingerMode == RINGER_MODE_VIBRATE) {
1785            if ((direction == AudioManager.ADJUST_LOWER)) {
1786                // Set it to silent, if it wasn't a long-press
1787                if (mPrevVolDirection != AudioManager.ADJUST_LOWER) {
1788                    newRingerMode = RINGER_MODE_SILENT;
1789                }
1790            } else if (direction == AudioManager.ADJUST_RAISE) {
1791                newRingerMode = RINGER_MODE_NORMAL;
1792            }
1793            adjustVolumeIndex = false;
1794        } else {
1795            if (direction == AudioManager.ADJUST_RAISE) {
1796                // exiting silent mode
1797                // If VIBRATE_IN_SILENT, then go into vibrate mode
1798                newRingerMode = vibeInSilent ? RINGER_MODE_VIBRATE : RINGER_MODE_NORMAL;
1799            }
1800            adjustVolumeIndex = false;
1801        }
1802
1803        if (newRingerMode != mRingerMode) {
1804            setRingerMode(newRingerMode);
1805        }
1806
1807        mPrevVolDirection = direction;
1808
1809        return adjustVolumeIndex;
1810    }
1811
1812    public boolean isStreamAffectedByRingerMode(int streamType) {
1813        return (mRingerModeAffectedStreams & (1 << streamType)) != 0;
1814    }
1815
1816    private boolean isStreamMutedByRingerMode(int streamType) {
1817        return (mRingerModeMutedStreams & (1 << streamType)) != 0;
1818    }
1819
1820    public boolean isStreamAffectedByMute(int streamType) {
1821        return (mMuteAffectedStreams & (1 << streamType)) != 0;
1822    }
1823
1824    private void ensureValidDirection(int direction) {
1825        if (direction < AudioManager.ADJUST_LOWER || direction > AudioManager.ADJUST_RAISE) {
1826            throw new IllegalArgumentException("Bad direction " + direction);
1827        }
1828    }
1829
1830    private void ensureValidStreamType(int streamType) {
1831        if (streamType < 0 || streamType >= mStreamStates.length) {
1832            throw new IllegalArgumentException("Bad stream type " + streamType);
1833        }
1834    }
1835
1836    private int getActiveStreamType(int suggestedStreamType) {
1837
1838        if (mVoiceCapable) {
1839            boolean isOffhook = false;
1840            try {
1841                ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
1842                if (phone != null) isOffhook = phone.isOffhook();
1843            } catch (RemoteException e) {
1844                Log.w(TAG, "Couldn't connect to phone service", e);
1845            }
1846
1847            if (isOffhook || getMode() == AudioManager.MODE_IN_COMMUNICATION) {
1848                if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION)
1849                        == AudioSystem.FORCE_BT_SCO) {
1850                    // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO...");
1851                    return AudioSystem.STREAM_BLUETOOTH_SCO;
1852                } else {
1853                    // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL...");
1854                    return AudioSystem.STREAM_VOICE_CALL;
1855                }
1856            } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0)) {
1857                // Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC...");
1858                return AudioSystem.STREAM_MUSIC;
1859            } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
1860                // Log.v(TAG, "getActiveStreamType: Forcing STREAM_RING..."
1861                //        + " b/c USE_DEFAULT_STREAM_TYPE...");
1862                return AudioSystem.STREAM_RING;
1863            } else {
1864                // Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType);
1865                return suggestedStreamType;
1866            }
1867        } else {
1868            if (getMode() == AudioManager.MODE_IN_COMMUNICATION) {
1869                if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION)
1870                        == AudioSystem.FORCE_BT_SCO) {
1871                    // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO...");
1872                    return AudioSystem.STREAM_BLUETOOTH_SCO;
1873                } else {
1874                    // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL...");
1875                    return AudioSystem.STREAM_VOICE_CALL;
1876                }
1877            } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_NOTIFICATION,
1878                            NOTIFICATION_VOLUME_DELAY_MS) ||
1879                       AudioSystem.isStreamActive(AudioSystem.STREAM_RING,
1880                            NOTIFICATION_VOLUME_DELAY_MS)) {
1881                // Log.v(TAG, "getActiveStreamType: Forcing STREAM_NOTIFICATION...");
1882                return AudioSystem.STREAM_NOTIFICATION;
1883            } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0) ||
1884                       (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE)) {
1885                // Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC "
1886                //        + " b/c USE_DEFAULT_STREAM_TYPE...");
1887                return AudioSystem.STREAM_MUSIC;
1888            } else {
1889                // Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType);
1890                return suggestedStreamType;
1891            }
1892        }
1893    }
1894
1895    private void broadcastRingerMode() {
1896        // Send sticky broadcast
1897        Intent broadcast = new Intent(AudioManager.RINGER_MODE_CHANGED_ACTION);
1898        broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, mRingerMode);
1899        broadcast.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
1900                | Intent.FLAG_RECEIVER_REPLACE_PENDING);
1901        long origCallerIdentityToken = Binder.clearCallingIdentity();
1902        mContext.sendStickyBroadcast(broadcast);
1903        Binder.restoreCallingIdentity(origCallerIdentityToken);
1904    }
1905
1906    private void broadcastVibrateSetting(int vibrateType) {
1907        // Send broadcast
1908        if (ActivityManagerNative.isSystemReady()) {
1909            Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION);
1910            broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType);
1911            broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType));
1912            mContext.sendBroadcast(broadcast);
1913        }
1914    }
1915
1916    // Message helper methods
1917    private static int getMsg(int baseMsg, int streamType) {
1918        return (baseMsg & 0xffff) | streamType << 16;
1919    }
1920
1921    private static int getMsgBase(int msg) {
1922        return msg & 0xffff;
1923    }
1924
1925    private static void sendMsg(Handler handler, int baseMsg, int streamType,
1926            int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) {
1927        int msg = (streamType == SHARED_MSG) ? baseMsg : getMsg(baseMsg, streamType);
1928
1929        if (existingMsgPolicy == SENDMSG_REPLACE) {
1930            handler.removeMessages(msg);
1931        } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) {
1932            return;
1933        }
1934
1935        handler
1936                .sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delay);
1937    }
1938
1939    boolean checkAudioSettingsPermission(String method) {
1940        if (mContext.checkCallingOrSelfPermission("android.permission.MODIFY_AUDIO_SETTINGS")
1941                == PackageManager.PERMISSION_GRANTED) {
1942            return true;
1943        }
1944        String msg = "Audio Settings Permission Denial: " + method + " from pid="
1945                + Binder.getCallingPid()
1946                + ", uid=" + Binder.getCallingUid();
1947        Log.w(TAG, msg);
1948        return false;
1949    }
1950
1951
1952    ///////////////////////////////////////////////////////////////////////////
1953    // Inner classes
1954    ///////////////////////////////////////////////////////////////////////////
1955
1956    public class VolumeStreamState {
1957        private final int mStreamType;
1958
1959        private String mVolumeIndexSettingName;
1960        private String mLastAudibleVolumeIndexSettingName;
1961        private int mIndexMax;
1962        private int mIndex;
1963        private int mLastAudibleIndex;
1964        private ArrayList<VolumeDeathHandler> mDeathHandlers; //handles mute/solo requests client death
1965
1966        private VolumeStreamState(String settingName, int streamType) {
1967
1968            setVolumeIndexSettingName(settingName);
1969
1970            mStreamType = streamType;
1971
1972            final ContentResolver cr = mContentResolver;
1973            mIndexMax = MAX_STREAM_VOLUME[streamType];
1974            mIndex = Settings.System.getInt(cr,
1975                                            mVolumeIndexSettingName,
1976                                            AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1977            mLastAudibleIndex = Settings.System.getInt(cr,
1978                                                       mLastAudibleVolumeIndexSettingName,
1979                                                       (mIndex > 0) ? mIndex : AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1980            AudioSystem.initStreamVolume(streamType, 0, mIndexMax);
1981            mIndexMax *= 10;
1982            mIndex = getValidIndex(10 * mIndex);
1983            mLastAudibleIndex = getValidIndex(10 * mLastAudibleIndex);
1984            setStreamVolumeIndex(streamType, mIndex);
1985            mDeathHandlers = new ArrayList<VolumeDeathHandler>();
1986        }
1987
1988        public void setVolumeIndexSettingName(String settingName) {
1989            mVolumeIndexSettingName = settingName;
1990            mLastAudibleVolumeIndexSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE;
1991        }
1992
1993        public boolean adjustIndex(int deltaIndex) {
1994            return setIndex(mIndex + deltaIndex * 10, true);
1995        }
1996
1997        public boolean setIndex(int index, boolean lastAudible) {
1998            int oldIndex = mIndex;
1999            mIndex = getValidIndex(index);
2000
2001            if (oldIndex != mIndex) {
2002                if (lastAudible) {
2003                    mLastAudibleIndex = mIndex;
2004                }
2005                // Apply change to all streams using this one as alias
2006                int numStreamTypes = AudioSystem.getNumStreamTypes();
2007                for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
2008                    if (streamType != mStreamType && STREAM_VOLUME_ALIAS[streamType] == mStreamType) {
2009                        mStreamStates[streamType].setIndex(rescaleIndex(mIndex, mStreamType, streamType), lastAudible);
2010                    }
2011                }
2012                return true;
2013            } else {
2014                return false;
2015            }
2016        }
2017
2018        public void setLastAudibleIndex(int index) {
2019            mLastAudibleIndex = getValidIndex(index);
2020        }
2021
2022        public void adjustLastAudibleIndex(int deltaIndex) {
2023            setLastAudibleIndex(mLastAudibleIndex + deltaIndex * 10);
2024        }
2025
2026        public int getMaxIndex() {
2027            return mIndexMax;
2028        }
2029
2030        public void mute(IBinder cb, boolean state) {
2031            VolumeDeathHandler handler = getDeathHandler(cb, state);
2032            if (handler == null) {
2033                Log.e(TAG, "Could not get client death handler for stream: "+mStreamType);
2034                return;
2035            }
2036            handler.mute(state);
2037        }
2038
2039        private int getValidIndex(int index) {
2040            if (index < 0) {
2041                return 0;
2042            } else if (index > mIndexMax) {
2043                return mIndexMax;
2044            }
2045
2046            return index;
2047        }
2048
2049        private class VolumeDeathHandler implements IBinder.DeathRecipient {
2050            private IBinder mICallback; // To be notified of client's death
2051            private int mMuteCount; // Number of active mutes for this client
2052
2053            VolumeDeathHandler(IBinder cb) {
2054                mICallback = cb;
2055            }
2056
2057            public void mute(boolean state) {
2058                synchronized(mDeathHandlers) {
2059                    if (state) {
2060                        if (mMuteCount == 0) {
2061                            // Register for client death notification
2062                            try {
2063                                // mICallback can be 0 if muted by AudioService
2064                                if (mICallback != null) {
2065                                    mICallback.linkToDeath(this, 0);
2066                                }
2067                                mDeathHandlers.add(this);
2068                                // If the stream is not yet muted by any client, set lvel to 0
2069                                if (muteCount() == 0) {
2070                                    setIndex(0, false);
2071                                    sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0,
2072                                            VolumeStreamState.this, 0);
2073                                }
2074                            } catch (RemoteException e) {
2075                                // Client has died!
2076                                binderDied();
2077                                mDeathHandlers.notify();
2078                                return;
2079                            }
2080                        } else {
2081                            Log.w(TAG, "stream: "+mStreamType+" was already muted by this client");
2082                        }
2083                        mMuteCount++;
2084                    } else {
2085                        if (mMuteCount == 0) {
2086                            Log.e(TAG, "unexpected unmute for stream: "+mStreamType);
2087                        } else {
2088                            mMuteCount--;
2089                            if (mMuteCount == 0) {
2090                                // Unregistr from client death notification
2091                                mDeathHandlers.remove(this);
2092                                // mICallback can be 0 if muted by AudioService
2093                                if (mICallback != null) {
2094                                    mICallback.unlinkToDeath(this, 0);
2095                                }
2096                                if (muteCount() == 0) {
2097                                    // If the stream is not muted any more, restore it's volume if
2098                                    // ringer mode allows it
2099                                    if (!isStreamAffectedByRingerMode(mStreamType) || mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
2100                                        setIndex(mLastAudibleIndex, false);
2101                                        sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0,
2102                                                VolumeStreamState.this, 0);
2103                                    }
2104                                }
2105                            }
2106                        }
2107                    }
2108                    mDeathHandlers.notify();
2109                }
2110            }
2111
2112            public void binderDied() {
2113                Log.w(TAG, "Volume service client died for stream: "+mStreamType);
2114                if (mMuteCount != 0) {
2115                    // Reset all active mute requests from this client.
2116                    mMuteCount = 1;
2117                    mute(false);
2118                }
2119            }
2120        }
2121
2122        private int muteCount() {
2123            int count = 0;
2124            int size = mDeathHandlers.size();
2125            for (int i = 0; i < size; i++) {
2126                count += mDeathHandlers.get(i).mMuteCount;
2127            }
2128            return count;
2129        }
2130
2131        private VolumeDeathHandler getDeathHandler(IBinder cb, boolean state) {
2132            synchronized(mDeathHandlers) {
2133                VolumeDeathHandler handler;
2134                int size = mDeathHandlers.size();
2135                for (int i = 0; i < size; i++) {
2136                    handler = mDeathHandlers.get(i);
2137                    if (cb == handler.mICallback) {
2138                        return handler;
2139                    }
2140                }
2141                // If this is the first mute request for this client, create a new
2142                // client death handler. Otherwise, it is an out of sequence unmute request.
2143                if (state) {
2144                    handler = new VolumeDeathHandler(cb);
2145                } else {
2146                    Log.w(TAG, "stream was not muted by this client");
2147                    handler = null;
2148                }
2149                return handler;
2150            }
2151        }
2152    }
2153
2154    /** Thread that handles native AudioSystem control. */
2155    private class AudioSystemThread extends Thread {
2156        AudioSystemThread() {
2157            super("AudioService");
2158        }
2159
2160        @Override
2161        public void run() {
2162            // Set this thread up so the handler will work on it
2163            Looper.prepare();
2164
2165            synchronized(AudioService.this) {
2166                mAudioHandler = new AudioHandler();
2167
2168                // Notify that the handler has been created
2169                AudioService.this.notify();
2170            }
2171
2172            // Listen for volume change requests that are set by VolumePanel
2173            Looper.loop();
2174        }
2175    }
2176
2177    /** Handles internal volume messages in separate volume thread. */
2178    private class AudioHandler extends Handler {
2179
2180        private void setSystemVolume(VolumeStreamState streamState) {
2181
2182            // Adjust volume
2183            setStreamVolumeIndex(streamState.mStreamType, streamState.mIndex);
2184
2185            // Apply change to all streams using this one as alias
2186            int numStreamTypes = AudioSystem.getNumStreamTypes();
2187            for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
2188                if (streamType != streamState.mStreamType &&
2189                    STREAM_VOLUME_ALIAS[streamType] == streamState.mStreamType) {
2190                    setStreamVolumeIndex(streamType, mStreamStates[streamType].mIndex);
2191                }
2192            }
2193
2194            // Post a persist volume msg
2195            sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamState.mStreamType,
2196                    SENDMSG_REPLACE, 1, 1, streamState, PERSIST_DELAY);
2197        }
2198
2199        private void persistVolume(VolumeStreamState streamState, boolean current, boolean lastAudible) {
2200            if (current) {
2201                System.putInt(mContentResolver, streamState.mVolumeIndexSettingName,
2202                              (streamState.mIndex + 5)/ 10);
2203            }
2204            if (lastAudible) {
2205                System.putInt(mContentResolver, streamState.mLastAudibleVolumeIndexSettingName,
2206                    (streamState.mLastAudibleIndex + 5) / 10);
2207            }
2208        }
2209
2210        private void persistRingerMode() {
2211            System.putInt(mContentResolver, System.MODE_RINGER, mRingerMode);
2212        }
2213
2214        private void persistVibrateSetting() {
2215            System.putInt(mContentResolver, System.VIBRATE_ON, mVibrateSetting);
2216        }
2217
2218        private void playSoundEffect(int effectType, int volume) {
2219            synchronized (mSoundEffectsLock) {
2220                if (mSoundPool == null) {
2221                    return;
2222                }
2223                float volFloat;
2224                // use default if volume is not specified by caller
2225                if (volume < 0) {
2226                    volFloat = (float)Math.pow(10, SOUND_EFFECT_VOLUME_DB/20);
2227                } else {
2228                    volFloat = (float) volume / 1000.0f;
2229                }
2230
2231                if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) {
2232                    mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1], volFloat, volFloat, 0, 0, 1.0f);
2233                } else {
2234                    MediaPlayer mediaPlayer = new MediaPlayer();
2235                    if (mediaPlayer != null) {
2236                        try {
2237                            String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effectType][0]];
2238                            mediaPlayer.setDataSource(filePath);
2239                            mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM);
2240                            mediaPlayer.prepare();
2241                            mediaPlayer.setVolume(volFloat, volFloat);
2242                            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
2243                                public void onCompletion(MediaPlayer mp) {
2244                                    cleanupPlayer(mp);
2245                                }
2246                            });
2247                            mediaPlayer.setOnErrorListener(new OnErrorListener() {
2248                                public boolean onError(MediaPlayer mp, int what, int extra) {
2249                                    cleanupPlayer(mp);
2250                                    return true;
2251                                }
2252                            });
2253                            mediaPlayer.start();
2254                        } catch (IOException ex) {
2255                            Log.w(TAG, "MediaPlayer IOException: "+ex);
2256                        } catch (IllegalArgumentException ex) {
2257                            Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex);
2258                        } catch (IllegalStateException ex) {
2259                            Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
2260                        }
2261                    }
2262                }
2263            }
2264        }
2265
2266        private void onHandlePersistMediaButtonReceiver(ComponentName receiver) {
2267            Settings.System.putString(mContentResolver, Settings.System.MEDIA_BUTTON_RECEIVER,
2268                    receiver == null ? "" : receiver.flattenToString());
2269        }
2270
2271        private void cleanupPlayer(MediaPlayer mp) {
2272            if (mp != null) {
2273                try {
2274                    mp.stop();
2275                    mp.release();
2276                } catch (IllegalStateException ex) {
2277                    Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
2278                }
2279            }
2280        }
2281
2282        private void setForceUse(int usage, int config) {
2283            AudioSystem.setForceUse(usage, config);
2284        }
2285
2286        @Override
2287        public void handleMessage(Message msg) {
2288            int baseMsgWhat = getMsgBase(msg.what);
2289
2290            switch (baseMsgWhat) {
2291
2292                case MSG_SET_SYSTEM_VOLUME:
2293                    setSystemVolume((VolumeStreamState) msg.obj);
2294                    break;
2295
2296                case MSG_PERSIST_VOLUME:
2297                    persistVolume((VolumeStreamState) msg.obj, (msg.arg1 != 0), (msg.arg2 != 0));
2298                    break;
2299
2300                case MSG_PERSIST_RINGER_MODE:
2301                    persistRingerMode();
2302                    break;
2303
2304                case MSG_PERSIST_VIBRATE_SETTING:
2305                    persistVibrateSetting();
2306                    break;
2307
2308                case MSG_MEDIA_SERVER_DIED:
2309                    if (!mMediaServerOk) {
2310                        Log.e(TAG, "Media server died.");
2311                        // Force creation of new IAudioFlinger interface so that we are notified
2312                        // when new media_server process is back to life.
2313                        AudioSystem.setErrorCallback(mAudioSystemCallback);
2314                        sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
2315                                null, 500);
2316                    }
2317                    break;
2318
2319                case MSG_MEDIA_SERVER_STARTED:
2320                    Log.e(TAG, "Media server started.");
2321                    // indicate to audio HAL that we start the reconfiguration phase after a media
2322                    // server crash
2323                    // Note that MSG_MEDIA_SERVER_STARTED message is only received when the media server
2324                    // process restarts after a crash, not the first time it is started.
2325                    AudioSystem.setParameters("restarting=true");
2326
2327                    // Restore device connection states
2328                    synchronized (mConnectedDevices) {
2329                        Set set = mConnectedDevices.entrySet();
2330                        Iterator i = set.iterator();
2331                        while(i.hasNext()){
2332                            Map.Entry device = (Map.Entry)i.next();
2333                            AudioSystem.setDeviceConnectionState(
2334                                                            ((Integer)device.getKey()).intValue(),
2335                                                            AudioSystem.DEVICE_STATE_AVAILABLE,
2336                                                            (String)device.getValue());
2337                        }
2338                    }
2339                    // Restore call state
2340                    AudioSystem.setPhoneState(mMode);
2341
2342                    // Restore forced usage for communcations and record
2343                    AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, mForcedUseForComm);
2344                    AudioSystem.setForceUse(AudioSystem.FOR_RECORD, mForcedUseForComm);
2345
2346                    // Restore stream volumes
2347                    int numStreamTypes = AudioSystem.getNumStreamTypes();
2348                    for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
2349                        int index;
2350                        VolumeStreamState streamState = mStreamStates[streamType];
2351                        AudioSystem.initStreamVolume(streamType, 0, (streamState.mIndexMax + 5) / 10);
2352                        if (streamState.muteCount() == 0) {
2353                            index = streamState.mIndex;
2354                        } else {
2355                            index = 0;
2356                        }
2357                        setStreamVolumeIndex(streamType, index);
2358                    }
2359
2360                    // Restore ringer mode
2361                    setRingerModeInt(getRingerMode(), false);
2362
2363                    // indicate the end of reconfiguration phase to audio HAL
2364                    AudioSystem.setParameters("restarting=false");
2365                    break;
2366
2367                case MSG_LOAD_SOUND_EFFECTS:
2368                    loadSoundEffects();
2369                    break;
2370
2371                case MSG_PLAY_SOUND_EFFECT:
2372                    playSoundEffect(msg.arg1, msg.arg2);
2373                    break;
2374
2375                case MSG_BTA2DP_DOCK_TIMEOUT:
2376                    // msg.obj  == address of BTA2DP device
2377                    synchronized (mConnectedDevices) {
2378                        makeA2dpDeviceUnavailableNow( (String) msg.obj );
2379                    }
2380                    break;
2381
2382                case MSG_SET_FORCE_USE:
2383                    setForceUse(msg.arg1, msg.arg2);
2384                    break;
2385
2386                case MSG_PERSIST_MEDIABUTTONRECEIVER:
2387                    onHandlePersistMediaButtonReceiver( (ComponentName) msg.obj );
2388                    break;
2389
2390                case MSG_RCDISPLAY_CLEAR:
2391                    onRcDisplayClear();
2392                    break;
2393
2394                case MSG_RCDISPLAY_UPDATE:
2395                    // msg.obj is guaranteed to be non null
2396                    onRcDisplayUpdate( (RemoteControlStackEntry) msg.obj, msg.arg1);
2397                    break;
2398
2399                case MSG_BT_HEADSET_CNCT_FAILED:
2400                    resetBluetoothSco();
2401                    break;
2402            }
2403        }
2404    }
2405
2406    private class SettingsObserver extends ContentObserver {
2407
2408        SettingsObserver() {
2409            super(new Handler());
2410            mContentResolver.registerContentObserver(Settings.System.getUriFor(
2411                Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this);
2412        }
2413
2414        @Override
2415        public void onChange(boolean selfChange) {
2416            super.onChange(selfChange);
2417            synchronized (mSettingsLock) {
2418                int ringerModeAffectedStreams = Settings.System.getInt(mContentResolver,
2419                       Settings.System.MODE_RINGER_STREAMS_AFFECTED,
2420                       ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)|
2421                       (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED)));
2422                if (mVoiceCapable) {
2423                    ringerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_MUSIC);
2424                } else {
2425                    ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_MUSIC);
2426                }
2427                if (ringerModeAffectedStreams != mRingerModeAffectedStreams) {
2428                    /*
2429                     * Ensure all stream types that should be affected by ringer mode
2430                     * are in the proper state.
2431                     */
2432                    mRingerModeAffectedStreams = ringerModeAffectedStreams;
2433                    setRingerModeInt(getRingerMode(), false);
2434                }
2435            }
2436        }
2437    }
2438
2439    // must be called synchronized on mConnectedDevices
2440    private void makeA2dpDeviceAvailable(String address) {
2441        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
2442                AudioSystem.DEVICE_STATE_AVAILABLE,
2443                address);
2444        // Reset A2DP suspend state each time a new sink is connected
2445        AudioSystem.setParameters("A2dpSuspended=false");
2446        mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP),
2447                address);
2448    }
2449
2450    // must be called synchronized on mConnectedDevices
2451    private void makeA2dpDeviceUnavailableNow(String address) {
2452        Intent noisyIntent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
2453        mContext.sendBroadcast(noisyIntent);
2454        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
2455                AudioSystem.DEVICE_STATE_UNAVAILABLE,
2456                address);
2457        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
2458    }
2459
2460    // must be called synchronized on mConnectedDevices
2461    private void makeA2dpDeviceUnavailableLater(String address) {
2462        // prevent any activity on the A2DP audio output to avoid unwanted
2463        // reconnection of the sink.
2464        AudioSystem.setParameters("A2dpSuspended=true");
2465        // the device will be made unavailable later, so consider it disconnected right away
2466        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
2467        // send the delayed message to make the device unavailable later
2468        Message msg = mAudioHandler.obtainMessage(MSG_BTA2DP_DOCK_TIMEOUT, address);
2469        mAudioHandler.sendMessageDelayed(msg, BTA2DP_DOCK_TIMEOUT_MILLIS);
2470
2471    }
2472
2473    // must be called synchronized on mConnectedDevices
2474    private void cancelA2dpDeviceTimeout() {
2475        mAudioHandler.removeMessages(MSG_BTA2DP_DOCK_TIMEOUT);
2476    }
2477
2478    // must be called synchronized on mConnectedDevices
2479    private boolean hasScheduledA2dpDockTimeout() {
2480        return mAudioHandler.hasMessages(MSG_BTA2DP_DOCK_TIMEOUT);
2481    }
2482
2483    private void handleA2dpConnectionStateChange(BluetoothDevice btDevice, int state)
2484    {
2485        if (btDevice == null) {
2486            return;
2487        }
2488        String address = btDevice.getAddress();
2489        if (!BluetoothAdapter.checkBluetoothAddress(address)) {
2490            address = "";
2491        }
2492        synchronized (mConnectedDevices) {
2493            boolean isConnected =
2494                (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP) &&
2495                 mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP).equals(address));
2496
2497            if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
2498                if (btDevice.isBluetoothDock()) {
2499                    if (state == BluetoothProfile.STATE_DISCONNECTED) {
2500                        // introduction of a delay for transient disconnections of docks when
2501                        // power is rapidly turned off/on, this message will be canceled if
2502                        // we reconnect the dock under a preset delay
2503                        makeA2dpDeviceUnavailableLater(address);
2504                        // the next time isConnected is evaluated, it will be false for the dock
2505                    }
2506                } else {
2507                    makeA2dpDeviceUnavailableNow(address);
2508                }
2509            } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
2510                if (btDevice.isBluetoothDock()) {
2511                    // this could be a reconnection after a transient disconnection
2512                    cancelA2dpDeviceTimeout();
2513                    mDockAddress = address;
2514                } else {
2515                    // this could be a connection of another A2DP device before the timeout of
2516                    // a dock: cancel the dock timeout, and make the dock unavailable now
2517                    if(hasScheduledA2dpDockTimeout()) {
2518                        cancelA2dpDeviceTimeout();
2519                        makeA2dpDeviceUnavailableNow(mDockAddress);
2520                    }
2521                }
2522                makeA2dpDeviceAvailable(address);
2523            }
2524        }
2525    }
2526
2527    /* cache of the address of the last dock the device was connected to */
2528    private String mDockAddress;
2529
2530    /**
2531     * Receiver for misc intent broadcasts the Phone app cares about.
2532     */
2533    private class AudioServiceBroadcastReceiver extends BroadcastReceiver {
2534        @Override
2535        public void onReceive(Context context, Intent intent) {
2536            String action = intent.getAction();
2537
2538            if (action.equals(Intent.ACTION_DOCK_EVENT)) {
2539                int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
2540                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
2541                int config;
2542                switch (dockState) {
2543                    case Intent.EXTRA_DOCK_STATE_DESK:
2544                        config = AudioSystem.FORCE_BT_DESK_DOCK;
2545                        break;
2546                    case Intent.EXTRA_DOCK_STATE_CAR:
2547                        config = AudioSystem.FORCE_BT_CAR_DOCK;
2548                        break;
2549                    case Intent.EXTRA_DOCK_STATE_LE_DESK:
2550                        config = AudioSystem.FORCE_ANALOG_DOCK;
2551                        break;
2552                    case Intent.EXTRA_DOCK_STATE_HE_DESK:
2553                        config = AudioSystem.FORCE_DIGITAL_DOCK;
2554                        break;
2555                    case Intent.EXTRA_DOCK_STATE_UNDOCKED:
2556                    default:
2557                        config = AudioSystem.FORCE_NONE;
2558                }
2559                AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
2560            } else if (action.equals(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED)) {
2561                int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
2562                                               BluetoothProfile.STATE_DISCONNECTED);
2563                BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
2564
2565                handleA2dpConnectionStateChange(btDevice, state);
2566            } else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
2567                int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
2568                                               BluetoothProfile.STATE_DISCONNECTED);
2569                int device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
2570                String address = null;
2571
2572                BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
2573                if (btDevice == null) {
2574                    return;
2575                }
2576
2577                address = btDevice.getAddress();
2578                BluetoothClass btClass = btDevice.getBluetoothClass();
2579                if (btClass != null) {
2580                    switch (btClass.getDeviceClass()) {
2581                    case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET:
2582                    case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
2583                        device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2584                        break;
2585                    case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO:
2586                        device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2587                        break;
2588                    }
2589                }
2590
2591                if (!BluetoothAdapter.checkBluetoothAddress(address)) {
2592                    address = "";
2593                }
2594
2595                synchronized (mConnectedDevices) {
2596                    boolean isConnected = (mConnectedDevices.containsKey(device) &&
2597                                           mConnectedDevices.get(device).equals(address));
2598
2599                    synchronized (mScoClients) {
2600                        if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
2601                            AudioSystem.setDeviceConnectionState(device,
2602                                                             AudioSystem.DEVICE_STATE_UNAVAILABLE,
2603                                                             address);
2604                            mConnectedDevices.remove(device);
2605                            mBluetoothHeadsetDevice = null;
2606                            resetBluetoothSco();
2607                        } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
2608                            AudioSystem.setDeviceConnectionState(device,
2609                                                                 AudioSystem.DEVICE_STATE_AVAILABLE,
2610                                                                 address);
2611                            mConnectedDevices.put(new Integer(device), address);
2612                            mBluetoothHeadsetDevice = btDevice;
2613                        }
2614                    }
2615                }
2616            } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
2617                int state = intent.getIntExtra("state", 0);
2618                int microphone = intent.getIntExtra("microphone", 0);
2619
2620                synchronized (mConnectedDevices) {
2621                    if (microphone != 0) {
2622                        boolean isConnected =
2623                            mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADSET);
2624                        if (state == 0 && isConnected) {
2625                            AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,
2626                                    AudioSystem.DEVICE_STATE_UNAVAILABLE,
2627                                    "");
2628                            mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADSET);
2629                        } else if (state == 1 && !isConnected)  {
2630                            AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,
2631                                    AudioSystem.DEVICE_STATE_AVAILABLE,
2632                                    "");
2633                            mConnectedDevices.put(
2634                                    new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADSET), "");
2635                        }
2636                    } else {
2637                        boolean isConnected =
2638                            mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE);
2639                        if (state == 0 && isConnected) {
2640                            AudioSystem.setDeviceConnectionState(
2641                                    AudioSystem.DEVICE_OUT_WIRED_HEADPHONE,
2642                                    AudioSystem.DEVICE_STATE_UNAVAILABLE,
2643                                    "");
2644                            mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE);
2645                        } else if (state == 1 && !isConnected)  {
2646                            AudioSystem.setDeviceConnectionState(
2647                                    AudioSystem.DEVICE_OUT_WIRED_HEADPHONE,
2648                                    AudioSystem.DEVICE_STATE_AVAILABLE,
2649                                    "");
2650                            mConnectedDevices.put(
2651                                    new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE), "");
2652                        }
2653                    }
2654                }
2655            } else if (action.equals(Intent.ACTION_USB_ANLG_HEADSET_PLUG)) {
2656                int state = intent.getIntExtra("state", 0);
2657                Log.v(TAG, "Broadcast Receiver: Got ACTION_USB_ANLG_HEADSET_PLUG, state = "+state);
2658                synchronized (mConnectedDevices) {
2659                    boolean isConnected =
2660                        mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET);
2661                    if (state == 0 && isConnected) {
2662                        AudioSystem.setDeviceConnectionState(
2663                                                        AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET,
2664                                                        AudioSystem.DEVICE_STATE_UNAVAILABLE,
2665                                                        "");
2666                        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET);
2667                    } else if (state == 1 && !isConnected)  {
2668                        AudioSystem.setDeviceConnectionState(
2669                                                        AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET,
2670                                                        AudioSystem.DEVICE_STATE_AVAILABLE,
2671                                                        "");
2672                        mConnectedDevices.put(
2673                                new Integer(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET), "");
2674                    }
2675                }
2676            } else if (action.equals(Intent.ACTION_HDMI_AUDIO_PLUG)) {
2677                int state = intent.getIntExtra("state", 0);
2678                Log.v(TAG, "Broadcast Receiver: Got ACTION_HDMI_AUDIO_PLUG, state = "+state);
2679                synchronized (mConnectedDevices) {
2680                    boolean isConnected =
2681                        mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_AUX_DIGITAL);
2682                    if (state == 0 && isConnected) {
2683                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_AUX_DIGITAL,
2684                                                             AudioSystem.DEVICE_STATE_UNAVAILABLE,
2685                                                             "");
2686                        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_AUX_DIGITAL);
2687                    } else if (state == 1 && !isConnected)  {
2688                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_AUX_DIGITAL,
2689                                                             AudioSystem.DEVICE_STATE_AVAILABLE,
2690                                                             "");
2691                        mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_AUX_DIGITAL), "");
2692                    }
2693                }
2694            } else if (action.equals(Intent.ACTION_USB_DGTL_HEADSET_PLUG)) {
2695                int state = intent.getIntExtra("state", 0);
2696                Log.v(TAG, "Broadcast Receiver: Got ACTION_USB_DGTL_HEADSET_PLUG, state = "+state);
2697                synchronized (mConnectedDevices) {
2698                    boolean isConnected =
2699                        mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET);
2700                    if (state == 0 && isConnected) {
2701                        AudioSystem.setDeviceConnectionState(
2702                                                         AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET,
2703                                                         AudioSystem.DEVICE_STATE_UNAVAILABLE,
2704                                                         "");
2705                        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET);
2706                    } else if (state == 1 && !isConnected)  {
2707                        AudioSystem.setDeviceConnectionState(
2708                                                         AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET,
2709                                                         AudioSystem.DEVICE_STATE_AVAILABLE,
2710                                                         "");
2711                        mConnectedDevices.put(
2712                                new Integer(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET), "");
2713                    }
2714                }
2715            } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) {
2716                boolean broadcast = false;
2717                int state = AudioManager.SCO_AUDIO_STATE_ERROR;
2718                synchronized (mScoClients) {
2719                    int btState = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1);
2720                    // broadcast intent if the connection was initated by AudioService
2721                    if (!mScoClients.isEmpty() &&
2722                            (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL ||
2723                             mScoAudioState == SCO_STATE_ACTIVATE_REQ ||
2724                             mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) {
2725                        broadcast = true;
2726                    }
2727                    switch (btState) {
2728                    case BluetoothHeadset.STATE_AUDIO_CONNECTED:
2729                        state = AudioManager.SCO_AUDIO_STATE_CONNECTED;
2730                        if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
2731                            mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
2732                            mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
2733                            mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
2734                        }
2735                        break;
2736                    case BluetoothHeadset.STATE_AUDIO_DISCONNECTED:
2737                        state = AudioManager.SCO_AUDIO_STATE_DISCONNECTED;
2738                        mScoAudioState = SCO_STATE_INACTIVE;
2739                        clearAllScoClients(0, false);
2740                        break;
2741                    case BluetoothHeadset.STATE_AUDIO_CONNECTING:
2742                        if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
2743                            mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
2744                            mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
2745                            mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
2746                        }
2747                    default:
2748                        // do not broadcast CONNECTING or invalid state
2749                        broadcast = false;
2750                        break;
2751                    }
2752                }
2753                if (broadcast) {
2754                    broadcastScoConnectionState(state);
2755                    //FIXME: this is to maintain compatibility with deprecated intent
2756                    // AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
2757                    Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
2758                    newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, state);
2759                    mContext.sendStickyBroadcast(newIntent);
2760                }
2761            } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
2762                mBootCompleted = true;
2763                sendMsg(mAudioHandler, MSG_LOAD_SOUND_EFFECTS, SHARED_MSG, SENDMSG_NOOP,
2764                        0, 0, null, 0);
2765
2766                mKeyguardManager =
2767                        (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
2768                mScoConnectionState = AudioManager.SCO_AUDIO_STATE_ERROR;
2769                resetBluetoothSco();
2770                getBluetoothHeadset();
2771                //FIXME: this is to maintain compatibility with deprecated intent
2772                // AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
2773                Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
2774                newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,
2775                        AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
2776                mContext.sendStickyBroadcast(newIntent);
2777
2778                BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
2779                if (adapter != null) {
2780                    adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
2781                                            BluetoothProfile.A2DP);
2782                }
2783
2784                if (mUseMasterVolume) {
2785                    // Send sticky broadcast for initial master mute state
2786                    sendMasterMuteUpdate(false, 0);
2787                }
2788            } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
2789                if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2790                    // a package is being removed, not replaced
2791                    String packageName = intent.getData().getSchemeSpecificPart();
2792                    if (packageName != null) {
2793                        removeMediaButtonReceiverForPackage(packageName);
2794                    }
2795                }
2796            } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
2797                AudioSystem.setParameters("screen_state=on");
2798            } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
2799                AudioSystem.setParameters("screen_state=off");
2800            }
2801        }
2802    }
2803
2804    //==========================================================================================
2805    // AudioFocus
2806    //==========================================================================================
2807
2808    /* constant to identify focus stack entry that is used to hold the focus while the phone
2809     * is ringing or during a call
2810     */
2811    private final static String IN_VOICE_COMM_FOCUS_ID = "AudioFocus_For_Phone_Ring_And_Calls";
2812
2813    private final static Object mAudioFocusLock = new Object();
2814
2815    private final static Object mRingingLock = new Object();
2816
2817    private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
2818        @Override
2819        public void onCallStateChanged(int state, String incomingNumber) {
2820            if (state == TelephonyManager.CALL_STATE_RINGING) {
2821                //Log.v(TAG, " CALL_STATE_RINGING");
2822                synchronized(mRingingLock) {
2823                    mIsRinging = true;
2824                }
2825            } else if ((state == TelephonyManager.CALL_STATE_OFFHOOK)
2826                    || (state == TelephonyManager.CALL_STATE_IDLE)) {
2827                synchronized(mRingingLock) {
2828                    mIsRinging = false;
2829                }
2830            }
2831        }
2832    };
2833
2834    private void notifyTopOfAudioFocusStack() {
2835        // notify the top of the stack it gained focus
2836        if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) {
2837            if (canReassignAudioFocus()) {
2838                try {
2839                    mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange(
2840                            AudioManager.AUDIOFOCUS_GAIN, mFocusStack.peek().mClientId);
2841                } catch (RemoteException e) {
2842                    Log.e(TAG, "Failure to signal gain of audio control focus due to "+ e);
2843                    e.printStackTrace();
2844                }
2845            }
2846        }
2847    }
2848
2849    private static class FocusStackEntry {
2850        public int mStreamType = -1;// no stream type
2851        public IAudioFocusDispatcher mFocusDispatcher = null;
2852        public IBinder mSourceRef = null;
2853        public String mClientId;
2854        public int mFocusChangeType;
2855        public AudioFocusDeathHandler mHandler;
2856        public String mPackageName;
2857        public int mCallingUid;
2858
2859        public FocusStackEntry() {
2860        }
2861
2862        public FocusStackEntry(int streamType, int duration,
2863                IAudioFocusDispatcher afl, IBinder source, String id, AudioFocusDeathHandler hdlr,
2864                String pn, int uid) {
2865            mStreamType = streamType;
2866            mFocusDispatcher = afl;
2867            mSourceRef = source;
2868            mClientId = id;
2869            mFocusChangeType = duration;
2870            mHandler = hdlr;
2871            mPackageName = pn;
2872            mCallingUid = uid;
2873        }
2874
2875        public void unlinkToDeath() {
2876            try {
2877                if (mSourceRef != null && mHandler != null) {
2878                    mSourceRef.unlinkToDeath(mHandler, 0);
2879                    mHandler = null;
2880                }
2881            } catch (java.util.NoSuchElementException e) {
2882                Log.e(TAG, "Encountered " + e + " in FocusStackEntry.unlinkToDeath()");
2883            }
2884        }
2885
2886        @Override
2887        protected void finalize() throws Throwable {
2888            unlinkToDeath(); // unlink exception handled inside method
2889            super.finalize();
2890        }
2891    }
2892
2893    private Stack<FocusStackEntry> mFocusStack = new Stack<FocusStackEntry>();
2894
2895    /**
2896     * Helper function:
2897     * Display in the log the current entries in the audio focus stack
2898     */
2899    private void dumpFocusStack(PrintWriter pw) {
2900        pw.println("\nAudio Focus stack entries:");
2901        synchronized(mAudioFocusLock) {
2902            Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
2903            while(stackIterator.hasNext()) {
2904                FocusStackEntry fse = stackIterator.next();
2905                pw.println("     source:" + fse.mSourceRef + " -- client: " + fse.mClientId
2906                        + " -- duration: " + fse.mFocusChangeType
2907                        + " -- uid: " + fse.mCallingUid);
2908            }
2909        }
2910    }
2911
2912    /**
2913     * Helper function:
2914     * Called synchronized on mAudioFocusLock
2915     * Remove a focus listener from the focus stack.
2916     * @param focusListenerToRemove the focus listener
2917     * @param signal if true and the listener was at the top of the focus stack, i.e. it was holding
2918     *   focus, notify the next item in the stack it gained focus.
2919     */
2920    private void removeFocusStackEntry(String clientToRemove, boolean signal) {
2921        // is the current top of the focus stack abandoning focus? (because of request, not death)
2922        if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientToRemove))
2923        {
2924            //Log.i(TAG, "   removeFocusStackEntry() removing top of stack");
2925            FocusStackEntry fse = mFocusStack.pop();
2926            fse.unlinkToDeath();
2927            if (signal) {
2928                // notify the new top of the stack it gained focus
2929                notifyTopOfAudioFocusStack();
2930                // there's a new top of the stack, let the remote control know
2931                synchronized(mRCStack) {
2932                    checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
2933                }
2934            }
2935        } else {
2936            // focus is abandoned by a client that's not at the top of the stack,
2937            // no need to update focus.
2938            Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
2939            while(stackIterator.hasNext()) {
2940                FocusStackEntry fse = (FocusStackEntry)stackIterator.next();
2941                if(fse.mClientId.equals(clientToRemove)) {
2942                    Log.i(TAG, " AudioFocus  abandonAudioFocus(): removing entry for "
2943                            + fse.mClientId);
2944                    stackIterator.remove();
2945                    fse.unlinkToDeath();
2946                }
2947            }
2948        }
2949    }
2950
2951    /**
2952     * Helper function:
2953     * Called synchronized on mAudioFocusLock
2954     * Remove focus listeners from the focus stack for a particular client when it has died.
2955     */
2956    private void removeFocusStackEntryForClient(IBinder cb) {
2957        // is the owner of the audio focus part of the client to remove?
2958        boolean isTopOfStackForClientToRemove = !mFocusStack.isEmpty() &&
2959                mFocusStack.peek().mSourceRef.equals(cb);
2960        Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
2961        while(stackIterator.hasNext()) {
2962            FocusStackEntry fse = (FocusStackEntry)stackIterator.next();
2963            if(fse.mSourceRef.equals(cb)) {
2964                Log.i(TAG, " AudioFocus  abandonAudioFocus(): removing entry for "
2965                        + fse.mClientId);
2966                stackIterator.remove();
2967                // the client just died, no need to unlink to its death
2968            }
2969        }
2970        if (isTopOfStackForClientToRemove) {
2971            // we removed an entry at the top of the stack:
2972            //  notify the new top of the stack it gained focus.
2973            notifyTopOfAudioFocusStack();
2974            // there's a new top of the stack, let the remote control know
2975            synchronized(mRCStack) {
2976                checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
2977            }
2978        }
2979    }
2980
2981    /**
2982     * Helper function:
2983     * Returns true if the system is in a state where the focus can be reevaluated, false otherwise.
2984     */
2985    private boolean canReassignAudioFocus() {
2986        // focus requests are rejected during a phone call or when the phone is ringing
2987        // this is equivalent to IN_VOICE_COMM_FOCUS_ID having the focus
2988        if (!mFocusStack.isEmpty() && IN_VOICE_COMM_FOCUS_ID.equals(mFocusStack.peek().mClientId)) {
2989            return false;
2990        }
2991        return true;
2992    }
2993
2994    /**
2995     * Inner class to monitor audio focus client deaths, and remove them from the audio focus
2996     * stack if necessary.
2997     */
2998    private class AudioFocusDeathHandler implements IBinder.DeathRecipient {
2999        private IBinder mCb; // To be notified of client's death
3000
3001        AudioFocusDeathHandler(IBinder cb) {
3002            mCb = cb;
3003        }
3004
3005        public void binderDied() {
3006            synchronized(mAudioFocusLock) {
3007                Log.w(TAG, "  AudioFocus   audio focus client died");
3008                removeFocusStackEntryForClient(mCb);
3009            }
3010        }
3011
3012        public IBinder getBinder() {
3013            return mCb;
3014        }
3015    }
3016
3017
3018    /** @see AudioManager#requestAudioFocus(IAudioFocusDispatcher, int, int) */
3019    public int requestAudioFocus(int mainStreamType, int focusChangeHint, IBinder cb,
3020            IAudioFocusDispatcher fd, String clientId, String callingPackageName) {
3021        Log.i(TAG, " AudioFocus  requestAudioFocus() from " + clientId);
3022        // the main stream type for the audio focus request is currently not used. It may
3023        // potentially be used to handle multiple stream type-dependent audio focuses.
3024
3025        // we need a valid binder callback for clients
3026        if (!cb.pingBinder()) {
3027            Log.e(TAG, " AudioFocus DOA client for requestAudioFocus(), aborting.");
3028            return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
3029        }
3030
3031        synchronized(mAudioFocusLock) {
3032            if (!canReassignAudioFocus()) {
3033                return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
3034            }
3035
3036            // handle the potential premature death of the new holder of the focus
3037            // (premature death == death before abandoning focus)
3038            // Register for client death notification
3039            AudioFocusDeathHandler afdh = new AudioFocusDeathHandler(cb);
3040            try {
3041                cb.linkToDeath(afdh, 0);
3042            } catch (RemoteException e) {
3043                // client has already died!
3044                Log.w(TAG, "AudioFocus  requestAudioFocus() could not link to "+cb+" binder death");
3045                return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
3046            }
3047
3048            if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientId)) {
3049                // if focus is already owned by this client and the reason for acquiring the focus
3050                // hasn't changed, don't do anything
3051                if (mFocusStack.peek().mFocusChangeType == focusChangeHint) {
3052                    // unlink death handler so it can be gc'ed.
3053                    // linkToDeath() creates a JNI global reference preventing collection.
3054                    cb.unlinkToDeath(afdh, 0);
3055                    return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
3056                }
3057                // the reason for the audio focus request has changed: remove the current top of
3058                // stack and respond as if we had a new focus owner
3059                FocusStackEntry fse = mFocusStack.pop();
3060                fse.unlinkToDeath();
3061            }
3062
3063            // notify current top of stack it is losing focus
3064            if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) {
3065                try {
3066                    mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange(
3067                            -1 * focusChangeHint, // loss and gain codes are inverse of each other
3068                            mFocusStack.peek().mClientId);
3069                } catch (RemoteException e) {
3070                    Log.e(TAG, " Failure to signal loss of focus due to "+ e);
3071                    e.printStackTrace();
3072                }
3073            }
3074
3075            // focus requester might already be somewhere below in the stack, remove it
3076            removeFocusStackEntry(clientId, false /* signal */);
3077
3078            // push focus requester at the top of the audio focus stack
3079            mFocusStack.push(new FocusStackEntry(mainStreamType, focusChangeHint, fd, cb,
3080                    clientId, afdh, callingPackageName, Binder.getCallingUid()));
3081
3082            // there's a new top of the stack, let the remote control know
3083            synchronized(mRCStack) {
3084                checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
3085            }
3086        }//synchronized(mAudioFocusLock)
3087
3088        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
3089    }
3090
3091    /** @see AudioManager#abandonAudioFocus(IAudioFocusDispatcher) */
3092    public int abandonAudioFocus(IAudioFocusDispatcher fl, String clientId) {
3093        Log.i(TAG, " AudioFocus  abandonAudioFocus() from " + clientId);
3094        try {
3095            // this will take care of notifying the new focus owner if needed
3096            synchronized(mAudioFocusLock) {
3097                removeFocusStackEntry(clientId, true);
3098            }
3099        } catch (java.util.ConcurrentModificationException cme) {
3100            // Catching this exception here is temporary. It is here just to prevent
3101            // a crash seen when the "Silent" notification is played. This is believed to be fixed
3102            // but this try catch block is left just to be safe.
3103            Log.e(TAG, "FATAL EXCEPTION AudioFocus  abandonAudioFocus() caused " + cme);
3104            cme.printStackTrace();
3105        }
3106
3107        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
3108    }
3109
3110
3111    public void unregisterAudioFocusClient(String clientId) {
3112        synchronized(mAudioFocusLock) {
3113            removeFocusStackEntry(clientId, false);
3114        }
3115    }
3116
3117
3118    //==========================================================================================
3119    // RemoteControl
3120    //==========================================================================================
3121    /**
3122     * Receiver for media button intents. Handles the dispatching of the media button event
3123     * to one of the registered listeners, or if there was none, resumes the intent broadcast
3124     * to the rest of the system.
3125     */
3126    private class MediaButtonBroadcastReceiver extends BroadcastReceiver {
3127        @Override
3128        public void onReceive(Context context, Intent intent) {
3129            String action = intent.getAction();
3130            if (!Intent.ACTION_MEDIA_BUTTON.equals(action)) {
3131                return;
3132            }
3133            KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
3134            if (event != null) {
3135                // if in a call or ringing, do not break the current phone app behavior
3136                // TODO modify this to let the phone app specifically get the RC focus
3137                //      add modify the phone app to take advantage of the new API
3138                synchronized(mRingingLock) {
3139                    if (mIsRinging || (getMode() == AudioSystem.MODE_IN_CALL) ||
3140                            (getMode() == AudioSystem.MODE_IN_COMMUNICATION) ||
3141                            (getMode() == AudioSystem.MODE_RINGTONE) ) {
3142                        return;
3143                    }
3144                }
3145                synchronized(mRCStack) {
3146                    if (!mRCStack.empty()) {
3147                        // create a new intent to fill in the extras of the registered PendingIntent
3148                        Intent targetedIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
3149                        Bundle extras = intent.getExtras();
3150                        if (extras != null) {
3151                            targetedIntent.putExtras(extras);
3152                            // trap the current broadcast
3153                            abortBroadcast();
3154                            //Log.v(TAG, " Sending intent" + targetedIntent);
3155                            // send the intent that was registered by the client
3156                            try {
3157                                mRCStack.peek().mMediaIntent.send(context, 0, targetedIntent);
3158                            } catch (CanceledException e) {
3159                                Log.e(TAG, "Error sending pending intent " + mRCStack.peek());
3160                                e.printStackTrace();
3161                            }
3162                        }
3163                    }
3164                }
3165            }
3166        }
3167    }
3168
3169    private final Object mCurrentRcLock = new Object();
3170    /**
3171     * The one remote control client which will receive a request for display information.
3172     * This object may be null.
3173     * Access protected by mCurrentRcLock.
3174     */
3175    private IRemoteControlClient mCurrentRcClient = null;
3176
3177    private final static int RC_INFO_NONE = 0;
3178    private final static int RC_INFO_ALL =
3179        RemoteControlClient.FLAG_INFORMATION_REQUEST_ALBUM_ART |
3180        RemoteControlClient.FLAG_INFORMATION_REQUEST_KEY_MEDIA |
3181        RemoteControlClient.FLAG_INFORMATION_REQUEST_METADATA |
3182        RemoteControlClient.FLAG_INFORMATION_REQUEST_PLAYSTATE;
3183
3184    /**
3185     * A monotonically increasing generation counter for mCurrentRcClient.
3186     * Only accessed with a lock on mCurrentRcLock.
3187     * No value wrap-around issues as we only act on equal values.
3188     */
3189    private int mCurrentRcClientGen = 0;
3190
3191    /**
3192     * Inner class to monitor remote control client deaths, and remove the client for the
3193     * remote control stack if necessary.
3194     */
3195    private class RcClientDeathHandler implements IBinder.DeathRecipient {
3196        private IBinder mCb; // To be notified of client's death
3197        private PendingIntent mMediaIntent;
3198
3199        RcClientDeathHandler(IBinder cb, PendingIntent pi) {
3200            mCb = cb;
3201            mMediaIntent = pi;
3202        }
3203
3204        public void binderDied() {
3205            Log.w(TAG, "  RemoteControlClient died");
3206            // remote control client died, make sure the displays don't use it anymore
3207            //  by setting its remote control client to null
3208            registerRemoteControlClient(mMediaIntent, null/*rcClient*/, null/*ignored*/);
3209        }
3210
3211        public IBinder getBinder() {
3212            return mCb;
3213        }
3214    }
3215
3216    private static class RemoteControlStackEntry {
3217        /**
3218         * The target for the ACTION_MEDIA_BUTTON events.
3219         * Always non null.
3220         */
3221        public PendingIntent mMediaIntent;
3222        /**
3223         * The registered media button event receiver.
3224         * Always non null.
3225         */
3226        public ComponentName mReceiverComponent;
3227        public String mCallingPackageName;
3228        public int mCallingUid;
3229        /**
3230         * Provides access to the information to display on the remote control.
3231         * May be null (when a media button event receiver is registered,
3232         *     but no remote control client has been registered) */
3233        public IRemoteControlClient mRcClient;
3234        public RcClientDeathHandler mRcClientDeathHandler;
3235
3236        /** precondition: mediaIntent != null, eventReceiver != null */
3237        public RemoteControlStackEntry(PendingIntent mediaIntent, ComponentName eventReceiver) {
3238            mMediaIntent = mediaIntent;
3239            mReceiverComponent = eventReceiver;
3240            mCallingUid = -1;
3241            mRcClient = null;
3242        }
3243
3244        public void unlinkToRcClientDeath() {
3245            if ((mRcClientDeathHandler != null) && (mRcClientDeathHandler.mCb != null)) {
3246                try {
3247                    mRcClientDeathHandler.mCb.unlinkToDeath(mRcClientDeathHandler, 0);
3248                    mRcClientDeathHandler = null;
3249                } catch (java.util.NoSuchElementException e) {
3250                    // not much we can do here
3251                    Log.e(TAG, "Encountered " + e + " in unlinkToRcClientDeath()");
3252                    e.printStackTrace();
3253                }
3254            }
3255        }
3256
3257        @Override
3258        protected void finalize() throws Throwable {
3259            unlinkToRcClientDeath();// unlink exception handled inside method
3260            super.finalize();
3261        }
3262    }
3263
3264    /**
3265     *  The stack of remote control event receivers.
3266     *  Code sections and methods that modify the remote control event receiver stack are
3267     *  synchronized on mRCStack, but also BEFORE on mFocusLock as any change in either
3268     *  stack, audio focus or RC, can lead to a change in the remote control display
3269     */
3270    private Stack<RemoteControlStackEntry> mRCStack = new Stack<RemoteControlStackEntry>();
3271
3272    /**
3273     * Helper function:
3274     * Display in the log the current entries in the remote control focus stack
3275     */
3276    private void dumpRCStack(PrintWriter pw) {
3277        pw.println("\nRemote Control stack entries:");
3278        synchronized(mRCStack) {
3279            Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3280            while(stackIterator.hasNext()) {
3281                RemoteControlStackEntry rcse = stackIterator.next();
3282                pw.println("  pi: " + rcse.mMediaIntent +
3283                        "  -- ercvr: " + rcse.mReceiverComponent +
3284                        "  -- client: " + rcse.mRcClient +
3285                        "  -- uid: " + rcse.mCallingUid);
3286            }
3287        }
3288    }
3289
3290    /**
3291     * Helper function:
3292     * Remove any entry in the remote control stack that has the same package name as packageName
3293     * Pre-condition: packageName != null
3294     */
3295    private void removeMediaButtonReceiverForPackage(String packageName) {
3296        synchronized(mRCStack) {
3297            if (mRCStack.empty()) {
3298                return;
3299            } else {
3300                RemoteControlStackEntry oldTop = mRCStack.peek();
3301                Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3302                // iterate over the stack entries
3303                while(stackIterator.hasNext()) {
3304                    RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
3305                    if (packageName.equalsIgnoreCase(rcse.mReceiverComponent.getPackageName())) {
3306                        // a stack entry is from the package being removed, remove it from the stack
3307                        stackIterator.remove();
3308                        rcse.unlinkToRcClientDeath();
3309                    }
3310                }
3311                if (mRCStack.empty()) {
3312                    // no saved media button receiver
3313                    mAudioHandler.sendMessage(
3314                            mAudioHandler.obtainMessage(MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0,
3315                                    null));
3316                } else if (oldTop != mRCStack.peek()) {
3317                    // the top of the stack has changed, save it in the system settings
3318                    // by posting a message to persist it
3319                    mAudioHandler.sendMessage(
3320                            mAudioHandler.obtainMessage(MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0,
3321                                    mRCStack.peek().mReceiverComponent));
3322                }
3323            }
3324        }
3325    }
3326
3327    /**
3328     * Helper function:
3329     * Restore remote control receiver from the system settings.
3330     */
3331    private void restoreMediaButtonReceiver() {
3332        String receiverName = Settings.System.getString(mContentResolver,
3333                Settings.System.MEDIA_BUTTON_RECEIVER);
3334        if ((null != receiverName) && !receiverName.isEmpty()) {
3335            ComponentName eventReceiver = ComponentName.unflattenFromString(receiverName);
3336            // construct a PendingIntent targeted to the restored component name
3337            // for the media button and register it
3338            Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
3339            //     the associated intent will be handled by the component being registered
3340            mediaButtonIntent.setComponent(eventReceiver);
3341            PendingIntent pi = PendingIntent.getBroadcast(mContext,
3342                    0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/);
3343            registerMediaButtonIntent(pi, eventReceiver);
3344        }
3345    }
3346
3347    /**
3348     * Helper function:
3349     * Set the new remote control receiver at the top of the RC focus stack.
3350     * precondition: mediaIntent != null, target != null
3351     */
3352    private void pushMediaButtonReceiver(PendingIntent mediaIntent, ComponentName target) {
3353        // already at top of stack?
3354        if (!mRCStack.empty() && mRCStack.peek().mMediaIntent.equals(mediaIntent)) {
3355            return;
3356        }
3357        Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3358        RemoteControlStackEntry rcse = null;
3359        boolean wasInsideStack = false;
3360        while(stackIterator.hasNext()) {
3361            rcse = (RemoteControlStackEntry)stackIterator.next();
3362            if(rcse.mMediaIntent.equals(mediaIntent)) {
3363                wasInsideStack = true;
3364                stackIterator.remove();
3365                break;
3366            }
3367        }
3368        if (!wasInsideStack) {
3369            rcse = new RemoteControlStackEntry(mediaIntent, target);
3370        }
3371        mRCStack.push(rcse);
3372
3373        // post message to persist the default media button receiver
3374        mAudioHandler.sendMessage( mAudioHandler.obtainMessage(
3375                MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0, target/*obj*/) );
3376    }
3377
3378    /**
3379     * Helper function:
3380     * Remove the remote control receiver from the RC focus stack.
3381     * precondition: pi != null
3382     */
3383    private void removeMediaButtonReceiver(PendingIntent pi) {
3384        Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3385        while(stackIterator.hasNext()) {
3386            RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
3387            if(rcse.mMediaIntent.equals(pi)) {
3388                stackIterator.remove();
3389                rcse.unlinkToRcClientDeath();
3390                break;
3391            }
3392        }
3393    }
3394
3395    /**
3396     * Helper function:
3397     * Called synchronized on mRCStack
3398     */
3399    private boolean isCurrentRcController(PendingIntent pi) {
3400        if (!mRCStack.empty() && mRCStack.peek().mMediaIntent.equals(pi)) {
3401            return true;
3402        }
3403        return false;
3404    }
3405
3406    //==========================================================================================
3407    // Remote control display / client
3408    //==========================================================================================
3409    /**
3410     * Update the remote control displays with the new "focused" client generation
3411     */
3412    private void setNewRcClientOnDisplays_syncRcsCurrc(int newClientGeneration,
3413            PendingIntent newMediaIntent, boolean clearing) {
3414        // NOTE: Only one IRemoteControlDisplay supported in this implementation
3415        if (mRcDisplay != null) {
3416            try {
3417                mRcDisplay.setCurrentClientId(
3418                        newClientGeneration, newMediaIntent, clearing);
3419            } catch (RemoteException e) {
3420                Log.e(TAG, "Dead display in setNewRcClientOnDisplays_syncRcsCurrc() "+e);
3421                // if we had a display before, stop monitoring its death
3422                rcDisplay_stopDeathMonitor_syncRcStack();
3423                mRcDisplay = null;
3424            }
3425        }
3426    }
3427
3428    /**
3429     * Update the remote control clients with the new "focused" client generation
3430     */
3431    private void setNewRcClientGenerationOnClients_syncRcsCurrc(int newClientGeneration) {
3432        Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3433        while(stackIterator.hasNext()) {
3434            RemoteControlStackEntry se = stackIterator.next();
3435            if ((se != null) && (se.mRcClient != null)) {
3436                try {
3437                    se.mRcClient.setCurrentClientGenerationId(newClientGeneration);
3438                } catch (RemoteException e) {
3439                    Log.w(TAG, "Dead client in setNewRcClientGenerationOnClients_syncRcsCurrc()"+e);
3440                    stackIterator.remove();
3441                    se.unlinkToRcClientDeath();
3442                }
3443            }
3444        }
3445    }
3446
3447    /**
3448     * Update the displays and clients with the new "focused" client generation and name
3449     * @param newClientGeneration the new generation value matching a client update
3450     * @param newClientEventReceiver the media button event receiver associated with the client.
3451     *    May be null, which implies there is no registered media button event receiver.
3452     * @param clearing true if the new client generation value maps to a remote control update
3453     *    where the display should be cleared.
3454     */
3455    private void setNewRcClient_syncRcsCurrc(int newClientGeneration,
3456            PendingIntent newMediaIntent, boolean clearing) {
3457        // send the new valid client generation ID to all displays
3458        setNewRcClientOnDisplays_syncRcsCurrc(newClientGeneration, newMediaIntent, clearing);
3459        // send the new valid client generation ID to all clients
3460        setNewRcClientGenerationOnClients_syncRcsCurrc(newClientGeneration);
3461    }
3462
3463    /**
3464     * Called when processing MSG_RCDISPLAY_CLEAR event
3465     */
3466    private void onRcDisplayClear() {
3467        if (DEBUG_RC) Log.i(TAG, "Clear remote control display");
3468
3469        synchronized(mRCStack) {
3470            synchronized(mCurrentRcLock) {
3471                mCurrentRcClientGen++;
3472                // synchronously update the displays and clients with the new client generation
3473                setNewRcClient_syncRcsCurrc(mCurrentRcClientGen,
3474                        null /*newMediaIntent*/, true /*clearing*/);
3475            }
3476        }
3477    }
3478
3479    /**
3480     * Called when processing MSG_RCDISPLAY_UPDATE event
3481     */
3482    private void onRcDisplayUpdate(RemoteControlStackEntry rcse, int flags /* USED ?*/) {
3483        synchronized(mRCStack) {
3484            synchronized(mCurrentRcLock) {
3485                if ((mCurrentRcClient != null) && (mCurrentRcClient.equals(rcse.mRcClient))) {
3486                    if (DEBUG_RC) Log.i(TAG, "Display/update remote control ");
3487
3488                    mCurrentRcClientGen++;
3489                    // synchronously update the displays and clients with
3490                    //      the new client generation
3491                    setNewRcClient_syncRcsCurrc(mCurrentRcClientGen,
3492                            rcse.mMediaIntent /*newMediaIntent*/,
3493                            false /*clearing*/);
3494
3495                    // tell the current client that it needs to send info
3496                    try {
3497                        mCurrentRcClient.onInformationRequested(mCurrentRcClientGen,
3498                                flags, mArtworkExpectedWidth, mArtworkExpectedHeight);
3499                    } catch (RemoteException e) {
3500                        Log.e(TAG, "Current valid remote client is dead: "+e);
3501                        mCurrentRcClient = null;
3502                    }
3503                } else {
3504                    // the remote control display owner has changed between the
3505                    // the message to update the display was sent, and the time it
3506                    // gets to be processed (now)
3507                }
3508            }
3509        }
3510    }
3511
3512
3513    /**
3514     * Helper function:
3515     * Called synchronized on mRCStack
3516     */
3517    private void clearRemoteControlDisplay_syncAfRcs() {
3518        synchronized(mCurrentRcLock) {
3519            mCurrentRcClient = null;
3520        }
3521        // will cause onRcDisplayClear() to be called in AudioService's handler thread
3522        mAudioHandler.sendMessage( mAudioHandler.obtainMessage(MSG_RCDISPLAY_CLEAR) );
3523    }
3524
3525    /**
3526     * Helper function for code readability: only to be called from
3527     *    checkUpdateRemoteControlDisplay_syncAfRcs() which checks the preconditions for
3528     *    this method.
3529     * Preconditions:
3530     *    - called synchronized mAudioFocusLock then on mRCStack
3531     *    - mRCStack.isEmpty() is false
3532     */
3533    private void updateRemoteControlDisplay_syncAfRcs(int infoChangedFlags) {
3534        RemoteControlStackEntry rcse = mRCStack.peek();
3535        int infoFlagsAboutToBeUsed = infoChangedFlags;
3536        // this is where we enforce opt-in for information display on the remote controls
3537        //   with the new AudioManager.registerRemoteControlClient() API
3538        if (rcse.mRcClient == null) {
3539            //Log.w(TAG, "Can't update remote control display with null remote control client");
3540            clearRemoteControlDisplay_syncAfRcs();
3541            return;
3542        }
3543        synchronized(mCurrentRcLock) {
3544            if (!rcse.mRcClient.equals(mCurrentRcClient)) {
3545                // new RC client, assume every type of information shall be queried
3546                infoFlagsAboutToBeUsed = RC_INFO_ALL;
3547            }
3548            mCurrentRcClient = rcse.mRcClient;
3549        }
3550        // will cause onRcDisplayUpdate() to be called in AudioService's handler thread
3551        mAudioHandler.sendMessage( mAudioHandler.obtainMessage(MSG_RCDISPLAY_UPDATE,
3552                infoFlagsAboutToBeUsed /* arg1 */, 0, rcse /* obj, != null */) );
3553    }
3554
3555    /**
3556     * Helper function:
3557     * Called synchronized on mAudioFocusLock, then mRCStack
3558     * Check whether the remote control display should be updated, triggers the update if required
3559     * @param infoChangedFlags the flags corresponding to the remote control client information
3560     *     that has changed, if applicable (checking for the update conditions might trigger a
3561     *     clear, rather than an update event).
3562     */
3563    private void checkUpdateRemoteControlDisplay_syncAfRcs(int infoChangedFlags) {
3564        // determine whether the remote control display should be refreshed
3565        // if either stack is empty, there is a mismatch, so clear the RC display
3566        if (mRCStack.isEmpty() || mFocusStack.isEmpty()) {
3567            clearRemoteControlDisplay_syncAfRcs();
3568            return;
3569        }
3570        // if the top of the two stacks belong to different packages, there is a mismatch, clear
3571        if ((mRCStack.peek().mCallingPackageName != null)
3572                && (mFocusStack.peek().mPackageName != null)
3573                && !(mRCStack.peek().mCallingPackageName.compareTo(
3574                        mFocusStack.peek().mPackageName) == 0)) {
3575            clearRemoteControlDisplay_syncAfRcs();
3576            return;
3577        }
3578        // if the audio focus didn't originate from the same Uid as the one in which the remote
3579        //   control information will be retrieved, clear
3580        if (mRCStack.peek().mCallingUid != mFocusStack.peek().mCallingUid) {
3581            clearRemoteControlDisplay_syncAfRcs();
3582            return;
3583        }
3584        // refresh conditions were verified: update the remote controls
3585        // ok to call: synchronized mAudioFocusLock then on mRCStack, mRCStack is not empty
3586        updateRemoteControlDisplay_syncAfRcs(infoChangedFlags);
3587    }
3588
3589    /**
3590     * see AudioManager.registerMediaButtonIntent(PendingIntent pi, ComponentName c)
3591     * precondition: mediaIntent != null, target != null
3592     */
3593    public void registerMediaButtonIntent(PendingIntent mediaIntent, ComponentName eventReceiver) {
3594        Log.i(TAG, "  Remote Control   registerMediaButtonIntent() for " + mediaIntent);
3595
3596        synchronized(mAudioFocusLock) {
3597            synchronized(mRCStack) {
3598                pushMediaButtonReceiver(mediaIntent, eventReceiver);
3599                // new RC client, assume every type of information shall be queried
3600                checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
3601            }
3602        }
3603    }
3604
3605    /**
3606     * see AudioManager.unregisterMediaButtonIntent(PendingIntent mediaIntent)
3607     * precondition: mediaIntent != null, eventReceiver != null
3608     */
3609    public void unregisterMediaButtonIntent(PendingIntent mediaIntent, ComponentName eventReceiver)
3610    {
3611        Log.i(TAG, "  Remote Control   unregisterMediaButtonIntent() for " + mediaIntent);
3612
3613        synchronized(mAudioFocusLock) {
3614            synchronized(mRCStack) {
3615                boolean topOfStackWillChange = isCurrentRcController(mediaIntent);
3616                removeMediaButtonReceiver(mediaIntent);
3617                if (topOfStackWillChange) {
3618                    // current RC client will change, assume every type of info needs to be queried
3619                    checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
3620                }
3621            }
3622        }
3623    }
3624
3625    /**
3626     * see AudioManager.registerRemoteControlClient(ComponentName eventReceiver, ...)
3627     * Note: using this method with rcClient == null is a way to "disable" the IRemoteControlClient
3628     *     without modifying the RC stack, but while still causing the display to refresh (will
3629     *     become blank as a result of this)
3630     */
3631    public void registerRemoteControlClient(PendingIntent mediaIntent,
3632            IRemoteControlClient rcClient, String callingPackageName) {
3633        if (DEBUG_RC) Log.i(TAG, "Register remote control client rcClient="+rcClient);
3634        synchronized(mAudioFocusLock) {
3635            synchronized(mRCStack) {
3636                // store the new display information
3637                Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3638                while(stackIterator.hasNext()) {
3639                    RemoteControlStackEntry rcse = stackIterator.next();
3640                    if(rcse.mMediaIntent.equals(mediaIntent)) {
3641                        // already had a remote control client?
3642                        if (rcse.mRcClientDeathHandler != null) {
3643                            // stop monitoring the old client's death
3644                            rcse.unlinkToRcClientDeath();
3645                        }
3646                        // save the new remote control client
3647                        rcse.mRcClient = rcClient;
3648                        rcse.mCallingPackageName = callingPackageName;
3649                        rcse.mCallingUid = Binder.getCallingUid();
3650                        if (rcClient == null) {
3651                            // here rcse.mRcClientDeathHandler is null;
3652                            break;
3653                        }
3654
3655                        // there is a new (non-null) client:
3656                        // 1/ give the new client the current display (if any)
3657                        if (mRcDisplay != null) {
3658                            try {
3659                                rcse.mRcClient.plugRemoteControlDisplay(mRcDisplay);
3660                            } catch (RemoteException e) {
3661                                Log.e(TAG, "Error connecting remote control display to client: "+e);
3662                                e.printStackTrace();
3663                            }
3664                        }
3665                        // 2/ monitor the new client's death
3666                        IBinder b = rcse.mRcClient.asBinder();
3667                        RcClientDeathHandler rcdh =
3668                                new RcClientDeathHandler(b, rcse.mMediaIntent);
3669                        try {
3670                            b.linkToDeath(rcdh, 0);
3671                        } catch (RemoteException e) {
3672                            // remote control client is DOA, disqualify it
3673                            Log.w(TAG, "registerRemoteControlClient() has a dead client " + b);
3674                            rcse.mRcClient = null;
3675                        }
3676                        rcse.mRcClientDeathHandler = rcdh;
3677                        break;
3678                    }
3679                }
3680                // if the eventReceiver is at the top of the stack
3681                // then check for potential refresh of the remote controls
3682                if (isCurrentRcController(mediaIntent)) {
3683                    checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
3684                }
3685            }
3686        }
3687    }
3688
3689    /**
3690     * see AudioManager.unregisterRemoteControlClient(PendingIntent pi, ...)
3691     * rcClient is guaranteed non-null
3692     */
3693    public void unregisterRemoteControlClient(PendingIntent mediaIntent,
3694            IRemoteControlClient rcClient) {
3695        synchronized(mAudioFocusLock) {
3696            synchronized(mRCStack) {
3697                Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3698                while(stackIterator.hasNext()) {
3699                    RemoteControlStackEntry rcse = stackIterator.next();
3700                    if ((rcse.mMediaIntent.equals(mediaIntent))
3701                            && rcClient.equals(rcse.mRcClient)) {
3702                        // we found the IRemoteControlClient to unregister
3703                        // stop monitoring its death
3704                        rcse.unlinkToRcClientDeath();
3705                        // reset the client-related fields
3706                        rcse.mRcClient = null;
3707                        rcse.mCallingPackageName = null;
3708                    }
3709                }
3710            }
3711        }
3712    }
3713
3714    /**
3715     * The remote control displays.
3716     * Access synchronized on mRCStack
3717     * NOTE: Only one IRemoteControlDisplay supported in this implementation
3718     */
3719    private IRemoteControlDisplay mRcDisplay;
3720    private RcDisplayDeathHandler mRcDisplayDeathHandler;
3721    private int mArtworkExpectedWidth = -1;
3722    private int mArtworkExpectedHeight = -1;
3723    /**
3724     * Inner class to monitor remote control display deaths, and unregister them from the list
3725     * of displays if necessary.
3726     */
3727    private class RcDisplayDeathHandler implements IBinder.DeathRecipient {
3728        private IBinder mCb; // To be notified of client's death
3729
3730        public RcDisplayDeathHandler(IBinder b) {
3731            if (DEBUG_RC) Log.i(TAG, "new RcDisplayDeathHandler for "+b);
3732            mCb = b;
3733        }
3734
3735        public void binderDied() {
3736            synchronized(mRCStack) {
3737                Log.w(TAG, "RemoteControl: display died");
3738                mRcDisplay = null;
3739            }
3740        }
3741
3742        public void unlinkToRcDisplayDeath() {
3743            if (DEBUG_RC) Log.i(TAG, "unlinkToRcDisplayDeath for "+mCb);
3744            try {
3745                mCb.unlinkToDeath(this, 0);
3746            } catch (java.util.NoSuchElementException e) {
3747                // not much we can do here, the display was being unregistered anyway
3748                Log.e(TAG, "Encountered " + e + " in unlinkToRcDisplayDeath()");
3749                e.printStackTrace();
3750            }
3751        }
3752
3753    }
3754
3755    private void rcDisplay_stopDeathMonitor_syncRcStack() {
3756        if (mRcDisplay != null) { // implies (mRcDisplayDeathHandler != null)
3757            // we had a display before, stop monitoring its death
3758            mRcDisplayDeathHandler.unlinkToRcDisplayDeath();
3759        }
3760    }
3761
3762    private void rcDisplay_startDeathMonitor_syncRcStack() {
3763        if (mRcDisplay != null) {
3764            // new non-null display, monitor its death
3765            IBinder b = mRcDisplay.asBinder();
3766            mRcDisplayDeathHandler = new RcDisplayDeathHandler(b);
3767            try {
3768                b.linkToDeath(mRcDisplayDeathHandler, 0);
3769            } catch (RemoteException e) {
3770                // remote control display is DOA, disqualify it
3771                Log.w(TAG, "registerRemoteControlDisplay() has a dead client " + b);
3772                mRcDisplay = null;
3773            }
3774        }
3775    }
3776
3777    /**
3778     * Register an IRemoteControlDisplay.
3779     * Notify all IRemoteControlClient of the new display and cause the RemoteControlClient
3780     * at the top of the stack to update the new display with its information.
3781     * Since only one IRemoteControlDisplay is supported, this will unregister the previous display.
3782     * @param rcd the IRemoteControlDisplay to register. No effect if null.
3783     */
3784    public void registerRemoteControlDisplay(IRemoteControlDisplay rcd) {
3785        if (DEBUG_RC) Log.d(TAG, ">>> registerRemoteControlDisplay("+rcd+")");
3786        synchronized(mAudioFocusLock) {
3787            synchronized(mRCStack) {
3788                if ((mRcDisplay == rcd) || (rcd == null)) {
3789                    return;
3790                }
3791                // if we had a display before, stop monitoring its death
3792                rcDisplay_stopDeathMonitor_syncRcStack();
3793                mRcDisplay = rcd;
3794                // new display, start monitoring its death
3795                rcDisplay_startDeathMonitor_syncRcStack();
3796
3797                // let all the remote control clients there is a new display
3798                // no need to unplug the previous because we only support one display
3799                // and the clients don't track the death of the display
3800                Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3801                while(stackIterator.hasNext()) {
3802                    RemoteControlStackEntry rcse = stackIterator.next();
3803                    if(rcse.mRcClient != null) {
3804                        try {
3805                            rcse.mRcClient.plugRemoteControlDisplay(mRcDisplay);
3806                        } catch (RemoteException e) {
3807                            Log.e(TAG, "Error connecting remote control display to client: " + e);
3808                            e.printStackTrace();
3809                        }
3810                    }
3811                }
3812
3813                // we have a new display, of which all the clients are now aware: have it be updated
3814                checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
3815            }
3816        }
3817    }
3818
3819    /**
3820     * Unregister an IRemoteControlDisplay.
3821     * Since only one IRemoteControlDisplay is supported, this has no effect if the one to
3822     *    unregister is not the current one.
3823     * @param rcd the IRemoteControlDisplay to unregister. No effect if null.
3824     */
3825    public void unregisterRemoteControlDisplay(IRemoteControlDisplay rcd) {
3826        if (DEBUG_RC) Log.d(TAG, "<<< unregisterRemoteControlDisplay("+rcd+")");
3827        synchronized(mRCStack) {
3828            // only one display here, so you can only unregister the current display
3829            if ((rcd == null) || (rcd != mRcDisplay)) {
3830                if (DEBUG_RC) Log.w(TAG, "    trying to unregister unregistered RCD");
3831                return;
3832            }
3833            // if we had a display before, stop monitoring its death
3834            rcDisplay_stopDeathMonitor_syncRcStack();
3835            mRcDisplay = null;
3836
3837            // disconnect this remote control display from all the clients
3838            Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3839            while(stackIterator.hasNext()) {
3840                RemoteControlStackEntry rcse = stackIterator.next();
3841                if(rcse.mRcClient != null) {
3842                    try {
3843                        rcse.mRcClient.unplugRemoteControlDisplay(rcd);
3844                    } catch (RemoteException e) {
3845                        Log.e(TAG, "Error disconnecting remote control display to client: " + e);
3846                        e.printStackTrace();
3847                    }
3848                }
3849            }
3850        }
3851    }
3852
3853    public void remoteControlDisplayUsesBitmapSize(IRemoteControlDisplay rcd, int w, int h) {
3854        synchronized(mRCStack) {
3855            // NOTE: Only one IRemoteControlDisplay supported in this implementation
3856            mArtworkExpectedWidth = w;
3857            mArtworkExpectedHeight = h;
3858        }
3859    }
3860
3861    @Override
3862    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3863        // TODO probably a lot more to do here than just the audio focus and remote control stacks
3864        dumpFocusStack(pw);
3865        dumpRCStack(pw);
3866    }
3867
3868
3869}
3870