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