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