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