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