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