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