AudioService.java revision 6243edd818b84adfbe712d5d233d6414b33653ac
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            BluetoothDevice btDevice;
1580            List<BluetoothDevice> deviceList;
1581            switch(profile) {
1582            case BluetoothProfile.A2DP:
1583                BluetoothA2dp a2dp = (BluetoothA2dp) proxy;
1584                deviceList = a2dp.getConnectedDevices();
1585                if (deviceList.size() > 0) {
1586                    btDevice = deviceList.get(0);
1587                    handleA2dpConnectionStateChange(btDevice, a2dp.getConnectionState(btDevice));
1588                }
1589                break;
1590
1591            case BluetoothProfile.HEADSET:
1592                synchronized (mScoClients) {
1593                    // Discard timeout message
1594                    mAudioHandler.removeMessages(MSG_BT_HEADSET_CNCT_FAILED);
1595                    mBluetoothHeadset = (BluetoothHeadset) proxy;
1596                    deviceList = mBluetoothHeadset.getConnectedDevices();
1597                    if (deviceList.size() > 0) {
1598                        mBluetoothHeadsetDevice = deviceList.get(0);
1599                    } else {
1600                        mBluetoothHeadsetDevice = null;
1601                    }
1602                    // Refresh SCO audio state
1603                    checkScoAudioState();
1604                    // Continue pending action if any
1605                    if (mScoAudioState == SCO_STATE_ACTIVATE_REQ ||
1606                            mScoAudioState == SCO_STATE_DEACTIVATE_REQ ||
1607                            mScoAudioState == SCO_STATE_DEACTIVATE_EXT_REQ) {
1608                        boolean status = false;
1609                        if (mBluetoothHeadsetDevice != null) {
1610                            switch (mScoAudioState) {
1611                            case SCO_STATE_ACTIVATE_REQ:
1612                                mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
1613                                status = mBluetoothHeadset.startScoUsingVirtualVoiceCall(
1614                                        mBluetoothHeadsetDevice);
1615                                break;
1616                            case SCO_STATE_DEACTIVATE_REQ:
1617                                status = mBluetoothHeadset.stopScoUsingVirtualVoiceCall(
1618                                        mBluetoothHeadsetDevice);
1619                                break;
1620                            case SCO_STATE_DEACTIVATE_EXT_REQ:
1621                                status = mBluetoothHeadset.stopVoiceRecognition(
1622                                        mBluetoothHeadsetDevice);
1623                            }
1624                        }
1625                        if (!status) {
1626                            sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED, 0,
1627                                    SENDMSG_REPLACE, 0, 0, null, 0);
1628                        }
1629                    }
1630                }
1631                break;
1632
1633            default:
1634                break;
1635            }
1636        }
1637        public void onServiceDisconnected(int profile) {
1638            switch(profile) {
1639            case BluetoothProfile.A2DP:
1640                synchronized (mConnectedDevices) {
1641                    if (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP)) {
1642                        makeA2dpDeviceUnavailableNow(
1643                                mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP));
1644                    }
1645                }
1646                break;
1647
1648            case BluetoothProfile.HEADSET:
1649                synchronized (mScoClients) {
1650                    mBluetoothHeadset = null;
1651                }
1652                break;
1653
1654            default:
1655                break;
1656            }
1657        }
1658    };
1659
1660    ///////////////////////////////////////////////////////////////////////////
1661    // Internal methods
1662    ///////////////////////////////////////////////////////////////////////////
1663
1664    /**
1665     * Checks if the adjustment should change ringer mode instead of just
1666     * adjusting volume. If so, this will set the proper ringer mode and volume
1667     * indices on the stream states.
1668     */
1669    private boolean checkForRingerModeChange(int oldIndex, int direction, int streamType) {
1670        boolean adjustVolumeIndex = true;
1671        int newRingerMode = mRingerMode;
1672        int uiIndex = (oldIndex + 5) / 10;
1673        boolean vibeInSilent = System.getInt(mContentResolver, System.VIBRATE_IN_SILENT, 1) == 1;
1674
1675        if (mRingerMode == RINGER_MODE_NORMAL) {
1676            if ((direction == AudioManager.ADJUST_LOWER) && (uiIndex <= 1)) {
1677                // enter silent mode if current index is the last audible one and not repeating a
1678                // volume key down
1679                if (vibeInSilent || mPrevVolDirection != AudioManager.ADJUST_LOWER) {
1680                    // "silent mode", but which one?
1681                    newRingerMode = vibeInSilent ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT;
1682                }
1683                if (uiIndex == 0 ||
1684                        (!vibeInSilent &&
1685                         mPrevVolDirection == AudioManager.ADJUST_LOWER &&
1686                         mVoiceCapable && streamType == AudioSystem.STREAM_RING)) {
1687                    adjustVolumeIndex = false;
1688                }
1689            }
1690        } else if (mRingerMode == RINGER_MODE_VIBRATE) {
1691            if ((direction == AudioManager.ADJUST_LOWER)) {
1692                // Set it to silent, if it wasn't a long-press
1693                if (mPrevVolDirection != AudioManager.ADJUST_LOWER) {
1694                    newRingerMode = RINGER_MODE_SILENT;
1695                }
1696            } else if (direction == AudioManager.ADJUST_RAISE) {
1697                newRingerMode = RINGER_MODE_NORMAL;
1698            }
1699            adjustVolumeIndex = false;
1700        } else {
1701            if (direction == AudioManager.ADJUST_RAISE) {
1702                // exiting silent mode
1703                // If VIBRATE_IN_SILENT, then go into vibrate mode
1704                newRingerMode = vibeInSilent ? RINGER_MODE_VIBRATE : RINGER_MODE_NORMAL;
1705            }
1706            adjustVolumeIndex = false;
1707        }
1708
1709        if (newRingerMode != mRingerMode) {
1710            setRingerMode(newRingerMode);
1711        }
1712
1713        mPrevVolDirection = direction;
1714
1715        return adjustVolumeIndex;
1716    }
1717
1718    public boolean isStreamAffectedByRingerMode(int streamType) {
1719        return (mRingerModeAffectedStreams & (1 << streamType)) != 0;
1720    }
1721
1722    private boolean isStreamMutedByRingerMode(int streamType) {
1723        return (mRingerModeMutedStreams & (1 << streamType)) != 0;
1724    }
1725
1726    public boolean isStreamAffectedByMute(int streamType) {
1727        return (mMuteAffectedStreams & (1 << streamType)) != 0;
1728    }
1729
1730    private void ensureValidDirection(int direction) {
1731        if (direction < AudioManager.ADJUST_LOWER || direction > AudioManager.ADJUST_RAISE) {
1732            throw new IllegalArgumentException("Bad direction " + direction);
1733        }
1734    }
1735
1736    private void ensureValidStreamType(int streamType) {
1737        if (streamType < 0 || streamType >= mStreamStates.length) {
1738            throw new IllegalArgumentException("Bad stream type " + streamType);
1739        }
1740    }
1741
1742    private int getActiveStreamType(int suggestedStreamType) {
1743
1744        if (mVoiceCapable) {
1745            boolean isOffhook = false;
1746            try {
1747                ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
1748                if (phone != null) isOffhook = phone.isOffhook();
1749            } catch (RemoteException e) {
1750                Log.w(TAG, "Couldn't connect to phone service", e);
1751            }
1752
1753            if (isOffhook || getMode() == AudioManager.MODE_IN_COMMUNICATION) {
1754                if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION)
1755                        == AudioSystem.FORCE_BT_SCO) {
1756                    // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO...");
1757                    return AudioSystem.STREAM_BLUETOOTH_SCO;
1758                } else {
1759                    // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL...");
1760                    return AudioSystem.STREAM_VOICE_CALL;
1761                }
1762            } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0)) {
1763                // Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC...");
1764                return AudioSystem.STREAM_MUSIC;
1765            } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
1766                // Log.v(TAG, "getActiveStreamType: Forcing STREAM_RING..."
1767                //        + " b/c USE_DEFAULT_STREAM_TYPE...");
1768                return AudioSystem.STREAM_RING;
1769            } else {
1770                // Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType);
1771                return suggestedStreamType;
1772            }
1773        } else {
1774            if (getMode() == AudioManager.MODE_IN_COMMUNICATION) {
1775                if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION)
1776                        == AudioSystem.FORCE_BT_SCO) {
1777                    // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO...");
1778                    return AudioSystem.STREAM_BLUETOOTH_SCO;
1779                } else {
1780                    // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL...");
1781                    return AudioSystem.STREAM_VOICE_CALL;
1782                }
1783            } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_NOTIFICATION,
1784                            NOTIFICATION_VOLUME_DELAY_MS) ||
1785                       AudioSystem.isStreamActive(AudioSystem.STREAM_RING,
1786                            NOTIFICATION_VOLUME_DELAY_MS)) {
1787                // Log.v(TAG, "getActiveStreamType: Forcing STREAM_NOTIFICATION...");
1788                return AudioSystem.STREAM_NOTIFICATION;
1789            } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0) ||
1790                       (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE)) {
1791                // Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC "
1792                //        + " b/c USE_DEFAULT_STREAM_TYPE...");
1793                return AudioSystem.STREAM_MUSIC;
1794            } else {
1795                // Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType);
1796                return suggestedStreamType;
1797            }
1798        }
1799    }
1800
1801    private void broadcastRingerMode() {
1802        // Send sticky broadcast
1803        Intent broadcast = new Intent(AudioManager.RINGER_MODE_CHANGED_ACTION);
1804        broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, mRingerMode);
1805        broadcast.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
1806                | Intent.FLAG_RECEIVER_REPLACE_PENDING);
1807        long origCallerIdentityToken = Binder.clearCallingIdentity();
1808        mContext.sendStickyBroadcast(broadcast);
1809        Binder.restoreCallingIdentity(origCallerIdentityToken);
1810    }
1811
1812    private void broadcastVibrateSetting(int vibrateType) {
1813        // Send broadcast
1814        if (ActivityManagerNative.isSystemReady()) {
1815            Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION);
1816            broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType);
1817            broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType));
1818            mContext.sendBroadcast(broadcast);
1819        }
1820    }
1821
1822    // Message helper methods
1823    private static int getMsg(int baseMsg, int streamType) {
1824        return (baseMsg & 0xffff) | streamType << 16;
1825    }
1826
1827    private static int getMsgBase(int msg) {
1828        return msg & 0xffff;
1829    }
1830
1831    private static void sendMsg(Handler handler, int baseMsg, int streamType,
1832            int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) {
1833        int msg = (streamType == SHARED_MSG) ? baseMsg : getMsg(baseMsg, streamType);
1834
1835        if (existingMsgPolicy == SENDMSG_REPLACE) {
1836            handler.removeMessages(msg);
1837        } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) {
1838            return;
1839        }
1840
1841        handler
1842                .sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delay);
1843    }
1844
1845    boolean checkAudioSettingsPermission(String method) {
1846        if (mContext.checkCallingOrSelfPermission("android.permission.MODIFY_AUDIO_SETTINGS")
1847                == PackageManager.PERMISSION_GRANTED) {
1848            return true;
1849        }
1850        String msg = "Audio Settings Permission Denial: " + method + " from pid="
1851                + Binder.getCallingPid()
1852                + ", uid=" + Binder.getCallingUid();
1853        Log.w(TAG, msg);
1854        return false;
1855    }
1856
1857
1858    ///////////////////////////////////////////////////////////////////////////
1859    // Inner classes
1860    ///////////////////////////////////////////////////////////////////////////
1861
1862    public class VolumeStreamState {
1863        private final int mStreamType;
1864
1865        private String mVolumeIndexSettingName;
1866        private String mLastAudibleVolumeIndexSettingName;
1867        private int mIndexMax;
1868        private int mIndex;
1869        private int mLastAudibleIndex;
1870        private ArrayList<VolumeDeathHandler> mDeathHandlers; //handles mute/solo requests client death
1871
1872        private VolumeStreamState(String settingName, int streamType) {
1873
1874            setVolumeIndexSettingName(settingName);
1875
1876            mStreamType = streamType;
1877
1878            final ContentResolver cr = mContentResolver;
1879            mIndexMax = MAX_STREAM_VOLUME[streamType];
1880            mIndex = Settings.System.getInt(cr,
1881                                            mVolumeIndexSettingName,
1882                                            AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1883            mLastAudibleIndex = Settings.System.getInt(cr,
1884                                                       mLastAudibleVolumeIndexSettingName,
1885                                                       (mIndex > 0) ? mIndex : AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1886            AudioSystem.initStreamVolume(streamType, 0, mIndexMax);
1887            mIndexMax *= 10;
1888            mIndex = getValidIndex(10 * mIndex);
1889            mLastAudibleIndex = getValidIndex(10 * mLastAudibleIndex);
1890            setStreamVolumeIndex(streamType, mIndex);
1891            mDeathHandlers = new ArrayList<VolumeDeathHandler>();
1892        }
1893
1894        public void setVolumeIndexSettingName(String settingName) {
1895            mVolumeIndexSettingName = settingName;
1896            mLastAudibleVolumeIndexSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE;
1897        }
1898
1899        public boolean adjustIndex(int deltaIndex) {
1900            return setIndex(mIndex + deltaIndex * 10, true);
1901        }
1902
1903        public boolean setIndex(int index, boolean lastAudible) {
1904            int oldIndex = mIndex;
1905            mIndex = getValidIndex(index);
1906
1907            if (oldIndex != mIndex) {
1908                if (lastAudible) {
1909                    mLastAudibleIndex = mIndex;
1910                }
1911                // Apply change to all streams using this one as alias
1912                int numStreamTypes = AudioSystem.getNumStreamTypes();
1913                for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
1914                    if (streamType != mStreamType && STREAM_VOLUME_ALIAS[streamType] == mStreamType) {
1915                        mStreamStates[streamType].setIndex(rescaleIndex(mIndex, mStreamType, streamType), lastAudible);
1916                    }
1917                }
1918                return true;
1919            } else {
1920                return false;
1921            }
1922        }
1923
1924        public void setLastAudibleIndex(int index) {
1925            mLastAudibleIndex = getValidIndex(index);
1926        }
1927
1928        public void adjustLastAudibleIndex(int deltaIndex) {
1929            setLastAudibleIndex(mLastAudibleIndex + deltaIndex * 10);
1930        }
1931
1932        public int getMaxIndex() {
1933            return mIndexMax;
1934        }
1935
1936        public void mute(IBinder cb, boolean state) {
1937            VolumeDeathHandler handler = getDeathHandler(cb, state);
1938            if (handler == null) {
1939                Log.e(TAG, "Could not get client death handler for stream: "+mStreamType);
1940                return;
1941            }
1942            handler.mute(state);
1943        }
1944
1945        private int getValidIndex(int index) {
1946            if (index < 0) {
1947                return 0;
1948            } else if (index > mIndexMax) {
1949                return mIndexMax;
1950            }
1951
1952            return index;
1953        }
1954
1955        private class VolumeDeathHandler implements IBinder.DeathRecipient {
1956            private IBinder mICallback; // To be notified of client's death
1957            private int mMuteCount; // Number of active mutes for this client
1958
1959            VolumeDeathHandler(IBinder cb) {
1960                mICallback = cb;
1961            }
1962
1963            public void mute(boolean state) {
1964                synchronized(mDeathHandlers) {
1965                    if (state) {
1966                        if (mMuteCount == 0) {
1967                            // Register for client death notification
1968                            try {
1969                                // mICallback can be 0 if muted by AudioService
1970                                if (mICallback != null) {
1971                                    mICallback.linkToDeath(this, 0);
1972                                }
1973                                mDeathHandlers.add(this);
1974                                // If the stream is not yet muted by any client, set lvel to 0
1975                                if (muteCount() == 0) {
1976                                    setIndex(0, false);
1977                                    sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0,
1978                                            VolumeStreamState.this, 0);
1979                                }
1980                            } catch (RemoteException e) {
1981                                // Client has died!
1982                                binderDied();
1983                                mDeathHandlers.notify();
1984                                return;
1985                            }
1986                        } else {
1987                            Log.w(TAG, "stream: "+mStreamType+" was already muted by this client");
1988                        }
1989                        mMuteCount++;
1990                    } else {
1991                        if (mMuteCount == 0) {
1992                            Log.e(TAG, "unexpected unmute for stream: "+mStreamType);
1993                        } else {
1994                            mMuteCount--;
1995                            if (mMuteCount == 0) {
1996                                // Unregistr from client death notification
1997                                mDeathHandlers.remove(this);
1998                                // mICallback can be 0 if muted by AudioService
1999                                if (mICallback != null) {
2000                                    mICallback.unlinkToDeath(this, 0);
2001                                }
2002                                if (muteCount() == 0) {
2003                                    // If the stream is not muted any more, restore it's volume if
2004                                    // ringer mode allows it
2005                                    if (!isStreamAffectedByRingerMode(mStreamType) || mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
2006                                        setIndex(mLastAudibleIndex, false);
2007                                        sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0,
2008                                                VolumeStreamState.this, 0);
2009                                    }
2010                                }
2011                            }
2012                        }
2013                    }
2014                    mDeathHandlers.notify();
2015                }
2016            }
2017
2018            public void binderDied() {
2019                Log.w(TAG, "Volume service client died for stream: "+mStreamType);
2020                if (mMuteCount != 0) {
2021                    // Reset all active mute requests from this client.
2022                    mMuteCount = 1;
2023                    mute(false);
2024                }
2025            }
2026        }
2027
2028        private int muteCount() {
2029            int count = 0;
2030            int size = mDeathHandlers.size();
2031            for (int i = 0; i < size; i++) {
2032                count += mDeathHandlers.get(i).mMuteCount;
2033            }
2034            return count;
2035        }
2036
2037        private VolumeDeathHandler getDeathHandler(IBinder cb, boolean state) {
2038            synchronized(mDeathHandlers) {
2039                VolumeDeathHandler handler;
2040                int size = mDeathHandlers.size();
2041                for (int i = 0; i < size; i++) {
2042                    handler = mDeathHandlers.get(i);
2043                    if (cb == handler.mICallback) {
2044                        return handler;
2045                    }
2046                }
2047                // If this is the first mute request for this client, create a new
2048                // client death handler. Otherwise, it is an out of sequence unmute request.
2049                if (state) {
2050                    handler = new VolumeDeathHandler(cb);
2051                } else {
2052                    Log.w(TAG, "stream was not muted by this client");
2053                    handler = null;
2054                }
2055                return handler;
2056            }
2057        }
2058    }
2059
2060    /** Thread that handles native AudioSystem control. */
2061    private class AudioSystemThread extends Thread {
2062        AudioSystemThread() {
2063            super("AudioService");
2064        }
2065
2066        @Override
2067        public void run() {
2068            // Set this thread up so the handler will work on it
2069            Looper.prepare();
2070
2071            synchronized(AudioService.this) {
2072                mAudioHandler = new AudioHandler();
2073
2074                // Notify that the handler has been created
2075                AudioService.this.notify();
2076            }
2077
2078            // Listen for volume change requests that are set by VolumePanel
2079            Looper.loop();
2080        }
2081    }
2082
2083    /** Handles internal volume messages in separate volume thread. */
2084    private class AudioHandler extends Handler {
2085
2086        private void setSystemVolume(VolumeStreamState streamState) {
2087
2088            // Adjust volume
2089            setStreamVolumeIndex(streamState.mStreamType, streamState.mIndex);
2090
2091            // Apply change to all streams using this one as alias
2092            int numStreamTypes = AudioSystem.getNumStreamTypes();
2093            for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
2094                if (streamType != streamState.mStreamType &&
2095                    STREAM_VOLUME_ALIAS[streamType] == streamState.mStreamType) {
2096                    setStreamVolumeIndex(streamType, mStreamStates[streamType].mIndex);
2097                }
2098            }
2099
2100            // Post a persist volume msg
2101            sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamState.mStreamType,
2102                    SENDMSG_REPLACE, 1, 1, streamState, PERSIST_DELAY);
2103        }
2104
2105        private void persistVolume(VolumeStreamState streamState, boolean current, boolean lastAudible) {
2106            if (current) {
2107                System.putInt(mContentResolver, streamState.mVolumeIndexSettingName,
2108                              (streamState.mIndex + 5)/ 10);
2109            }
2110            if (lastAudible) {
2111                System.putInt(mContentResolver, streamState.mLastAudibleVolumeIndexSettingName,
2112                    (streamState.mLastAudibleIndex + 5) / 10);
2113            }
2114        }
2115
2116        private void persistRingerMode() {
2117            System.putInt(mContentResolver, System.MODE_RINGER, mRingerMode);
2118        }
2119
2120        private void persistVibrateSetting() {
2121            System.putInt(mContentResolver, System.VIBRATE_ON, mVibrateSetting);
2122        }
2123
2124        private void playSoundEffect(int effectType, int volume) {
2125            synchronized (mSoundEffectsLock) {
2126                if (mSoundPool == null) {
2127                    return;
2128                }
2129                float volFloat;
2130                // use default if volume is not specified by caller
2131                if (volume < 0) {
2132                    volFloat = (float)Math.pow(10, SOUND_EFFECT_VOLUME_DB/20);
2133                } else {
2134                    volFloat = (float) volume / 1000.0f;
2135                }
2136
2137                if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) {
2138                    mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1], volFloat, volFloat, 0, 0, 1.0f);
2139                } else {
2140                    MediaPlayer mediaPlayer = new MediaPlayer();
2141                    if (mediaPlayer != null) {
2142                        try {
2143                            String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effectType][0]];
2144                            mediaPlayer.setDataSource(filePath);
2145                            mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM);
2146                            mediaPlayer.prepare();
2147                            mediaPlayer.setVolume(volFloat, volFloat);
2148                            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
2149                                public void onCompletion(MediaPlayer mp) {
2150                                    cleanupPlayer(mp);
2151                                }
2152                            });
2153                            mediaPlayer.setOnErrorListener(new OnErrorListener() {
2154                                public boolean onError(MediaPlayer mp, int what, int extra) {
2155                                    cleanupPlayer(mp);
2156                                    return true;
2157                                }
2158                            });
2159                            mediaPlayer.start();
2160                        } catch (IOException ex) {
2161                            Log.w(TAG, "MediaPlayer IOException: "+ex);
2162                        } catch (IllegalArgumentException ex) {
2163                            Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex);
2164                        } catch (IllegalStateException ex) {
2165                            Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
2166                        }
2167                    }
2168                }
2169            }
2170        }
2171
2172        private void onHandlePersistMediaButtonReceiver(ComponentName receiver) {
2173            Settings.System.putString(mContentResolver, Settings.System.MEDIA_BUTTON_RECEIVER,
2174                    receiver == null ? "" : receiver.flattenToString());
2175        }
2176
2177        private void cleanupPlayer(MediaPlayer mp) {
2178            if (mp != null) {
2179                try {
2180                    mp.stop();
2181                    mp.release();
2182                } catch (IllegalStateException ex) {
2183                    Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
2184                }
2185            }
2186        }
2187
2188        private void setForceUse(int usage, int config) {
2189            AudioSystem.setForceUse(usage, config);
2190        }
2191
2192        @Override
2193        public void handleMessage(Message msg) {
2194            int baseMsgWhat = getMsgBase(msg.what);
2195
2196            switch (baseMsgWhat) {
2197
2198                case MSG_SET_SYSTEM_VOLUME:
2199                    setSystemVolume((VolumeStreamState) msg.obj);
2200                    break;
2201
2202                case MSG_PERSIST_VOLUME:
2203                    persistVolume((VolumeStreamState) msg.obj, (msg.arg1 != 0), (msg.arg2 != 0));
2204                    break;
2205
2206                case MSG_PERSIST_RINGER_MODE:
2207                    persistRingerMode();
2208                    break;
2209
2210                case MSG_PERSIST_VIBRATE_SETTING:
2211                    persistVibrateSetting();
2212                    break;
2213
2214                case MSG_MEDIA_SERVER_DIED:
2215                    if (!mMediaServerOk) {
2216                        Log.e(TAG, "Media server died.");
2217                        // Force creation of new IAudioFlinger interface so that we are notified
2218                        // when new media_server process is back to life.
2219                        AudioSystem.setErrorCallback(mAudioSystemCallback);
2220                        sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
2221                                null, 500);
2222                    }
2223                    break;
2224
2225                case MSG_MEDIA_SERVER_STARTED:
2226                    Log.e(TAG, "Media server started.");
2227                    // indicate to audio HAL that we start the reconfiguration phase after a media
2228                    // server crash
2229                    // Note that MSG_MEDIA_SERVER_STARTED message is only received when the media server
2230                    // process restarts after a crash, not the first time it is started.
2231                    AudioSystem.setParameters("restarting=true");
2232
2233                    // Restore device connection states
2234                    synchronized (mConnectedDevices) {
2235                        Set set = mConnectedDevices.entrySet();
2236                        Iterator i = set.iterator();
2237                        while(i.hasNext()){
2238                            Map.Entry device = (Map.Entry)i.next();
2239                            AudioSystem.setDeviceConnectionState(
2240                                                            ((Integer)device.getKey()).intValue(),
2241                                                            AudioSystem.DEVICE_STATE_AVAILABLE,
2242                                                            (String)device.getValue());
2243                        }
2244                    }
2245                    // Restore call state
2246                    AudioSystem.setPhoneState(mMode);
2247
2248                    // Restore forced usage for communcations and record
2249                    AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, mForcedUseForComm);
2250                    AudioSystem.setForceUse(AudioSystem.FOR_RECORD, mForcedUseForComm);
2251
2252                    // Restore stream volumes
2253                    int numStreamTypes = AudioSystem.getNumStreamTypes();
2254                    for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
2255                        int index;
2256                        VolumeStreamState streamState = mStreamStates[streamType];
2257                        AudioSystem.initStreamVolume(streamType, 0, (streamState.mIndexMax + 5) / 10);
2258                        if (streamState.muteCount() == 0) {
2259                            index = streamState.mIndex;
2260                        } else {
2261                            index = 0;
2262                        }
2263                        setStreamVolumeIndex(streamType, index);
2264                    }
2265
2266                    // Restore ringer mode
2267                    setRingerModeInt(getRingerMode(), false);
2268
2269                    // indicate the end of reconfiguration phase to audio HAL
2270                    AudioSystem.setParameters("restarting=false");
2271                    break;
2272
2273                case MSG_LOAD_SOUND_EFFECTS:
2274                    loadSoundEffects();
2275                    break;
2276
2277                case MSG_PLAY_SOUND_EFFECT:
2278                    playSoundEffect(msg.arg1, msg.arg2);
2279                    break;
2280
2281                case MSG_BTA2DP_DOCK_TIMEOUT:
2282                    // msg.obj  == address of BTA2DP device
2283                    synchronized (mConnectedDevices) {
2284                        makeA2dpDeviceUnavailableNow( (String) msg.obj );
2285                    }
2286                    break;
2287
2288                case MSG_SET_FORCE_USE:
2289                    setForceUse(msg.arg1, msg.arg2);
2290                    break;
2291
2292                case MSG_PERSIST_MEDIABUTTONRECEIVER:
2293                    onHandlePersistMediaButtonReceiver( (ComponentName) msg.obj );
2294                    break;
2295
2296                case MSG_RCDISPLAY_CLEAR:
2297                    onRcDisplayClear();
2298                    break;
2299
2300                case MSG_RCDISPLAY_UPDATE:
2301                    // msg.obj is guaranteed to be non null
2302                    onRcDisplayUpdate( (RemoteControlStackEntry) msg.obj, msg.arg1);
2303                    break;
2304
2305                case MSG_BT_HEADSET_CNCT_FAILED:
2306                    resetBluetoothSco();
2307                    break;
2308            }
2309        }
2310    }
2311
2312    private class SettingsObserver extends ContentObserver {
2313
2314        SettingsObserver() {
2315            super(new Handler());
2316            mContentResolver.registerContentObserver(Settings.System.getUriFor(
2317                Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this);
2318        }
2319
2320        @Override
2321        public void onChange(boolean selfChange) {
2322            super.onChange(selfChange);
2323            synchronized (mSettingsLock) {
2324                int ringerModeAffectedStreams = Settings.System.getInt(mContentResolver,
2325                       Settings.System.MODE_RINGER_STREAMS_AFFECTED,
2326                       ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)|
2327                       (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED)));
2328                if (mVoiceCapable) {
2329                    ringerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_MUSIC);
2330                } else {
2331                    ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_MUSIC);
2332                }
2333                if (ringerModeAffectedStreams != mRingerModeAffectedStreams) {
2334                    /*
2335                     * Ensure all stream types that should be affected by ringer mode
2336                     * are in the proper state.
2337                     */
2338                    mRingerModeAffectedStreams = ringerModeAffectedStreams;
2339                    setRingerModeInt(getRingerMode(), false);
2340                }
2341            }
2342        }
2343    }
2344
2345    // must be called synchronized on mConnectedDevices
2346    private void makeA2dpDeviceAvailable(String address) {
2347        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
2348                AudioSystem.DEVICE_STATE_AVAILABLE,
2349                address);
2350        // Reset A2DP suspend state each time a new sink is connected
2351        AudioSystem.setParameters("A2dpSuspended=false");
2352        mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP),
2353                address);
2354    }
2355
2356    // must be called synchronized on mConnectedDevices
2357    private void makeA2dpDeviceUnavailableNow(String address) {
2358        Intent noisyIntent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
2359        mContext.sendBroadcast(noisyIntent);
2360        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
2361                AudioSystem.DEVICE_STATE_UNAVAILABLE,
2362                address);
2363        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
2364    }
2365
2366    // must be called synchronized on mConnectedDevices
2367    private void makeA2dpDeviceUnavailableLater(String address) {
2368        // prevent any activity on the A2DP audio output to avoid unwanted
2369        // reconnection of the sink.
2370        AudioSystem.setParameters("A2dpSuspended=true");
2371        // the device will be made unavailable later, so consider it disconnected right away
2372        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
2373        // send the delayed message to make the device unavailable later
2374        Message msg = mAudioHandler.obtainMessage(MSG_BTA2DP_DOCK_TIMEOUT, address);
2375        mAudioHandler.sendMessageDelayed(msg, BTA2DP_DOCK_TIMEOUT_MILLIS);
2376
2377    }
2378
2379    // must be called synchronized on mConnectedDevices
2380    private void cancelA2dpDeviceTimeout() {
2381        mAudioHandler.removeMessages(MSG_BTA2DP_DOCK_TIMEOUT);
2382    }
2383
2384    // must be called synchronized on mConnectedDevices
2385    private boolean hasScheduledA2dpDockTimeout() {
2386        return mAudioHandler.hasMessages(MSG_BTA2DP_DOCK_TIMEOUT);
2387    }
2388
2389    private void handleA2dpConnectionStateChange(BluetoothDevice btDevice, int state)
2390    {
2391        if (btDevice == null) {
2392            return;
2393        }
2394        String address = btDevice.getAddress();
2395        if (!BluetoothAdapter.checkBluetoothAddress(address)) {
2396            address = "";
2397        }
2398        synchronized (mConnectedDevices) {
2399            boolean isConnected =
2400                (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP) &&
2401                 mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP).equals(address));
2402
2403            if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
2404                if (btDevice.isBluetoothDock()) {
2405                    if (state == BluetoothProfile.STATE_DISCONNECTED) {
2406                        // introduction of a delay for transient disconnections of docks when
2407                        // power is rapidly turned off/on, this message will be canceled if
2408                        // we reconnect the dock under a preset delay
2409                        makeA2dpDeviceUnavailableLater(address);
2410                        // the next time isConnected is evaluated, it will be false for the dock
2411                    }
2412                } else {
2413                    makeA2dpDeviceUnavailableNow(address);
2414                }
2415            } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
2416                if (btDevice.isBluetoothDock()) {
2417                    // this could be a reconnection after a transient disconnection
2418                    cancelA2dpDeviceTimeout();
2419                    mDockAddress = address;
2420                } else {
2421                    // this could be a connection of another A2DP device before the timeout of
2422                    // a dock: cancel the dock timeout, and make the dock unavailable now
2423                    if(hasScheduledA2dpDockTimeout()) {
2424                        cancelA2dpDeviceTimeout();
2425                        makeA2dpDeviceUnavailableNow(mDockAddress);
2426                    }
2427                }
2428                makeA2dpDeviceAvailable(address);
2429            }
2430        }
2431    }
2432
2433    /* cache of the address of the last dock the device was connected to */
2434    private String mDockAddress;
2435
2436    /**
2437     * Receiver for misc intent broadcasts the Phone app cares about.
2438     */
2439    private class AudioServiceBroadcastReceiver extends BroadcastReceiver {
2440        @Override
2441        public void onReceive(Context context, Intent intent) {
2442            String action = intent.getAction();
2443
2444            if (action.equals(Intent.ACTION_DOCK_EVENT)) {
2445                int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
2446                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
2447                int config;
2448                switch (dockState) {
2449                    case Intent.EXTRA_DOCK_STATE_DESK:
2450                        config = AudioSystem.FORCE_BT_DESK_DOCK;
2451                        break;
2452                    case Intent.EXTRA_DOCK_STATE_CAR:
2453                        config = AudioSystem.FORCE_BT_CAR_DOCK;
2454                        break;
2455                    case Intent.EXTRA_DOCK_STATE_LE_DESK:
2456                        config = AudioSystem.FORCE_ANALOG_DOCK;
2457                        break;
2458                    case Intent.EXTRA_DOCK_STATE_HE_DESK:
2459                        config = AudioSystem.FORCE_DIGITAL_DOCK;
2460                        break;
2461                    case Intent.EXTRA_DOCK_STATE_UNDOCKED:
2462                    default:
2463                        config = AudioSystem.FORCE_NONE;
2464                }
2465                AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
2466            } else if (action.equals(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED)) {
2467                int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
2468                                               BluetoothProfile.STATE_DISCONNECTED);
2469                BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
2470
2471                handleA2dpConnectionStateChange(btDevice, state);
2472            } else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
2473                int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
2474                                               BluetoothProfile.STATE_DISCONNECTED);
2475                int device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
2476                String address = null;
2477
2478                BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
2479                if (btDevice == null) {
2480                    return;
2481                }
2482
2483                address = btDevice.getAddress();
2484                BluetoothClass btClass = btDevice.getBluetoothClass();
2485                if (btClass != null) {
2486                    switch (btClass.getDeviceClass()) {
2487                    case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET:
2488                    case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
2489                        device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2490                        break;
2491                    case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO:
2492                        device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2493                        break;
2494                    }
2495                }
2496
2497                if (!BluetoothAdapter.checkBluetoothAddress(address)) {
2498                    address = "";
2499                }
2500
2501                synchronized (mConnectedDevices) {
2502                    boolean isConnected = (mConnectedDevices.containsKey(device) &&
2503                                           mConnectedDevices.get(device).equals(address));
2504
2505                    synchronized (mScoClients) {
2506                        if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
2507                            AudioSystem.setDeviceConnectionState(device,
2508                                                             AudioSystem.DEVICE_STATE_UNAVAILABLE,
2509                                                             address);
2510                            mConnectedDevices.remove(device);
2511                            mBluetoothHeadsetDevice = null;
2512                            resetBluetoothSco();
2513                        } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
2514                            AudioSystem.setDeviceConnectionState(device,
2515                                                                 AudioSystem.DEVICE_STATE_AVAILABLE,
2516                                                                 address);
2517                            mConnectedDevices.put(new Integer(device), address);
2518                            mBluetoothHeadsetDevice = btDevice;
2519                        }
2520                    }
2521                }
2522            } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
2523                int state = intent.getIntExtra("state", 0);
2524                int microphone = intent.getIntExtra("microphone", 0);
2525
2526                synchronized (mConnectedDevices) {
2527                    if (microphone != 0) {
2528                        boolean isConnected =
2529                            mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADSET);
2530                        if (state == 0 && isConnected) {
2531                            AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,
2532                                    AudioSystem.DEVICE_STATE_UNAVAILABLE,
2533                                    "");
2534                            mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADSET);
2535                        } else if (state == 1 && !isConnected)  {
2536                            AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,
2537                                    AudioSystem.DEVICE_STATE_AVAILABLE,
2538                                    "");
2539                            mConnectedDevices.put(
2540                                    new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADSET), "");
2541                        }
2542                    } else {
2543                        boolean isConnected =
2544                            mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE);
2545                        if (state == 0 && isConnected) {
2546                            AudioSystem.setDeviceConnectionState(
2547                                    AudioSystem.DEVICE_OUT_WIRED_HEADPHONE,
2548                                    AudioSystem.DEVICE_STATE_UNAVAILABLE,
2549                                    "");
2550                            mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE);
2551                        } else if (state == 1 && !isConnected)  {
2552                            AudioSystem.setDeviceConnectionState(
2553                                    AudioSystem.DEVICE_OUT_WIRED_HEADPHONE,
2554                                    AudioSystem.DEVICE_STATE_AVAILABLE,
2555                                    "");
2556                            mConnectedDevices.put(
2557                                    new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE), "");
2558                        }
2559                    }
2560                }
2561            } else if (action.equals(Intent.ACTION_USB_ANLG_HEADSET_PLUG)) {
2562                int state = intent.getIntExtra("state", 0);
2563                Log.v(TAG, "Broadcast Receiver: Got ACTION_USB_ANLG_HEADSET_PLUG, state = "+state);
2564                synchronized (mConnectedDevices) {
2565                    boolean isConnected =
2566                        mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET);
2567                    if (state == 0 && isConnected) {
2568                        AudioSystem.setDeviceConnectionState(
2569                                                        AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET,
2570                                                        AudioSystem.DEVICE_STATE_UNAVAILABLE,
2571                                                        "");
2572                        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET);
2573                    } else if (state == 1 && !isConnected)  {
2574                        AudioSystem.setDeviceConnectionState(
2575                                                        AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET,
2576                                                        AudioSystem.DEVICE_STATE_AVAILABLE,
2577                                                        "");
2578                        mConnectedDevices.put(
2579                                new Integer(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET), "");
2580                    }
2581                }
2582            } else if (action.equals(Intent.ACTION_HDMI_AUDIO_PLUG)) {
2583                int state = intent.getIntExtra("state", 0);
2584                Log.v(TAG, "Broadcast Receiver: Got ACTION_HDMI_AUDIO_PLUG, state = "+state);
2585                synchronized (mConnectedDevices) {
2586                    boolean isConnected =
2587                        mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_AUX_DIGITAL);
2588                    if (state == 0 && isConnected) {
2589                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_AUX_DIGITAL,
2590                                                             AudioSystem.DEVICE_STATE_UNAVAILABLE,
2591                                                             "");
2592                        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_AUX_DIGITAL);
2593                    } else if (state == 1 && !isConnected)  {
2594                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_AUX_DIGITAL,
2595                                                             AudioSystem.DEVICE_STATE_AVAILABLE,
2596                                                             "");
2597                        mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_AUX_DIGITAL), "");
2598                    }
2599                }
2600            } else if (action.equals(Intent.ACTION_USB_DGTL_HEADSET_PLUG)) {
2601                int state = intent.getIntExtra("state", 0);
2602                Log.v(TAG, "Broadcast Receiver: Got ACTION_USB_DGTL_HEADSET_PLUG, state = "+state);
2603                synchronized (mConnectedDevices) {
2604                    boolean isConnected =
2605                        mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET);
2606                    if (state == 0 && isConnected) {
2607                        AudioSystem.setDeviceConnectionState(
2608                                                         AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET,
2609                                                         AudioSystem.DEVICE_STATE_UNAVAILABLE,
2610                                                         "");
2611                        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET);
2612                    } else if (state == 1 && !isConnected)  {
2613                        AudioSystem.setDeviceConnectionState(
2614                                                         AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET,
2615                                                         AudioSystem.DEVICE_STATE_AVAILABLE,
2616                                                         "");
2617                        mConnectedDevices.put(
2618                                new Integer(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET), "");
2619                    }
2620                }
2621            } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) {
2622                boolean broadcast = false;
2623                int state = AudioManager.SCO_AUDIO_STATE_ERROR;
2624                synchronized (mScoClients) {
2625                    int btState = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1);
2626                    // broadcast intent if the connection was initated by AudioService
2627                    if (!mScoClients.isEmpty() &&
2628                            (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL ||
2629                             mScoAudioState == SCO_STATE_ACTIVATE_REQ ||
2630                             mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) {
2631                        broadcast = true;
2632                    }
2633                    switch (btState) {
2634                    case BluetoothHeadset.STATE_AUDIO_CONNECTED:
2635                        state = AudioManager.SCO_AUDIO_STATE_CONNECTED;
2636                        if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
2637                            mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
2638                            mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
2639                            mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
2640                        }
2641                        break;
2642                    case BluetoothHeadset.STATE_AUDIO_DISCONNECTED:
2643                        state = AudioManager.SCO_AUDIO_STATE_DISCONNECTED;
2644                        mScoAudioState = SCO_STATE_INACTIVE;
2645                        clearAllScoClients(0, false);
2646                        break;
2647                    case BluetoothHeadset.STATE_AUDIO_CONNECTING:
2648                        if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL &&
2649                            mScoAudioState != SCO_STATE_DEACTIVATE_REQ &&
2650                            mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) {
2651                            mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL;
2652                        }
2653                    default:
2654                        // do not broadcast CONNECTING or invalid state
2655                        broadcast = false;
2656                        break;
2657                    }
2658                }
2659                if (broadcast) {
2660                    broadcastScoConnectionState(state);
2661                    //FIXME: this is to maintain compatibility with deprecated intent
2662                    // AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
2663                    Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
2664                    newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, state);
2665                    mContext.sendStickyBroadcast(newIntent);
2666                }
2667            } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
2668                mBootCompleted = true;
2669                sendMsg(mAudioHandler, MSG_LOAD_SOUND_EFFECTS, SHARED_MSG, SENDMSG_NOOP,
2670                        0, 0, null, 0);
2671
2672                mKeyguardManager =
2673                        (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
2674                mScoConnectionState = AudioManager.SCO_AUDIO_STATE_ERROR;
2675                resetBluetoothSco();
2676                getBluetoothHeadset();
2677                //FIXME: this is to maintain compatibility with deprecated intent
2678                // AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate.
2679                Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
2680                newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,
2681                        AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
2682                mContext.sendStickyBroadcast(newIntent);
2683
2684                BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
2685                if (adapter != null) {
2686                    adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
2687                                            BluetoothProfile.A2DP);
2688                }
2689            } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
2690                if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2691                    // a package is being removed, not replaced
2692                    String packageName = intent.getData().getSchemeSpecificPart();
2693                    if (packageName != null) {
2694                        removeMediaButtonReceiverForPackage(packageName);
2695                    }
2696                }
2697            } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
2698                AudioSystem.setParameters("screen_state=on");
2699            } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
2700                AudioSystem.setParameters("screen_state=off");
2701            }
2702        }
2703    }
2704
2705    //==========================================================================================
2706    // AudioFocus
2707    //==========================================================================================
2708
2709    /* constant to identify focus stack entry that is used to hold the focus while the phone
2710     * is ringing or during a call
2711     */
2712    private final static String IN_VOICE_COMM_FOCUS_ID = "AudioFocus_For_Phone_Ring_And_Calls";
2713
2714    private final static Object mAudioFocusLock = new Object();
2715
2716    private final static Object mRingingLock = new Object();
2717
2718    private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
2719        @Override
2720        public void onCallStateChanged(int state, String incomingNumber) {
2721            if (state == TelephonyManager.CALL_STATE_RINGING) {
2722                //Log.v(TAG, " CALL_STATE_RINGING");
2723                synchronized(mRingingLock) {
2724                    mIsRinging = true;
2725                }
2726            } else if ((state == TelephonyManager.CALL_STATE_OFFHOOK)
2727                    || (state == TelephonyManager.CALL_STATE_IDLE)) {
2728                synchronized(mRingingLock) {
2729                    mIsRinging = false;
2730                }
2731            }
2732        }
2733    };
2734
2735    private void notifyTopOfAudioFocusStack() {
2736        // notify the top of the stack it gained focus
2737        if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) {
2738            if (canReassignAudioFocus()) {
2739                try {
2740                    mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange(
2741                            AudioManager.AUDIOFOCUS_GAIN, mFocusStack.peek().mClientId);
2742                } catch (RemoteException e) {
2743                    Log.e(TAG, "Failure to signal gain of audio control focus due to "+ e);
2744                    e.printStackTrace();
2745                }
2746            }
2747        }
2748    }
2749
2750    private static class FocusStackEntry {
2751        public int mStreamType = -1;// no stream type
2752        public IAudioFocusDispatcher mFocusDispatcher = null;
2753        public IBinder mSourceRef = null;
2754        public String mClientId;
2755        public int mFocusChangeType;
2756        public AudioFocusDeathHandler mHandler;
2757        public String mPackageName;
2758        public int mCallingUid;
2759
2760        public FocusStackEntry() {
2761        }
2762
2763        public FocusStackEntry(int streamType, int duration,
2764                IAudioFocusDispatcher afl, IBinder source, String id, AudioFocusDeathHandler hdlr,
2765                String pn, int uid) {
2766            mStreamType = streamType;
2767            mFocusDispatcher = afl;
2768            mSourceRef = source;
2769            mClientId = id;
2770            mFocusChangeType = duration;
2771            mHandler = hdlr;
2772            mPackageName = pn;
2773            mCallingUid = uid;
2774        }
2775
2776        public void unlinkToDeath() {
2777            try {
2778                if (mSourceRef != null && mHandler != null) {
2779                    mSourceRef.unlinkToDeath(mHandler, 0);
2780                    mHandler = null;
2781                }
2782            } catch (java.util.NoSuchElementException e) {
2783                Log.e(TAG, "Encountered " + e + " in FocusStackEntry.unlinkToDeath()");
2784            }
2785        }
2786
2787        @Override
2788        protected void finalize() throws Throwable {
2789            unlinkToDeath(); // unlink exception handled inside method
2790            super.finalize();
2791        }
2792    }
2793
2794    private Stack<FocusStackEntry> mFocusStack = new Stack<FocusStackEntry>();
2795
2796    /**
2797     * Helper function:
2798     * Display in the log the current entries in the audio focus stack
2799     */
2800    private void dumpFocusStack(PrintWriter pw) {
2801        pw.println("\nAudio Focus stack entries:");
2802        synchronized(mAudioFocusLock) {
2803            Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
2804            while(stackIterator.hasNext()) {
2805                FocusStackEntry fse = stackIterator.next();
2806                pw.println("     source:" + fse.mSourceRef + " -- client: " + fse.mClientId
2807                        + " -- duration: " + fse.mFocusChangeType
2808                        + " -- uid: " + fse.mCallingUid);
2809            }
2810        }
2811    }
2812
2813    /**
2814     * Helper function:
2815     * Called synchronized on mAudioFocusLock
2816     * Remove a focus listener from the focus stack.
2817     * @param focusListenerToRemove the focus listener
2818     * @param signal if true and the listener was at the top of the focus stack, i.e. it was holding
2819     *   focus, notify the next item in the stack it gained focus.
2820     */
2821    private void removeFocusStackEntry(String clientToRemove, boolean signal) {
2822        // is the current top of the focus stack abandoning focus? (because of request, not death)
2823        if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientToRemove))
2824        {
2825            //Log.i(TAG, "   removeFocusStackEntry() removing top of stack");
2826            FocusStackEntry fse = mFocusStack.pop();
2827            fse.unlinkToDeath();
2828            if (signal) {
2829                // notify the new top of the stack it gained focus
2830                notifyTopOfAudioFocusStack();
2831                // there's a new top of the stack, let the remote control know
2832                synchronized(mRCStack) {
2833                    checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
2834                }
2835            }
2836        } else {
2837            // focus is abandoned by a client that's not at the top of the stack,
2838            // no need to update focus.
2839            Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
2840            while(stackIterator.hasNext()) {
2841                FocusStackEntry fse = (FocusStackEntry)stackIterator.next();
2842                if(fse.mClientId.equals(clientToRemove)) {
2843                    Log.i(TAG, " AudioFocus  abandonAudioFocus(): removing entry for "
2844                            + fse.mClientId);
2845                    stackIterator.remove();
2846                    fse.unlinkToDeath();
2847                }
2848            }
2849        }
2850    }
2851
2852    /**
2853     * Helper function:
2854     * Called synchronized on mAudioFocusLock
2855     * Remove focus listeners from the focus stack for a particular client when it has died.
2856     */
2857    private void removeFocusStackEntryForClient(IBinder cb) {
2858        // is the owner of the audio focus part of the client to remove?
2859        boolean isTopOfStackForClientToRemove = !mFocusStack.isEmpty() &&
2860                mFocusStack.peek().mSourceRef.equals(cb);
2861        Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
2862        while(stackIterator.hasNext()) {
2863            FocusStackEntry fse = (FocusStackEntry)stackIterator.next();
2864            if(fse.mSourceRef.equals(cb)) {
2865                Log.i(TAG, " AudioFocus  abandonAudioFocus(): removing entry for "
2866                        + fse.mClientId);
2867                stackIterator.remove();
2868                // the client just died, no need to unlink to its death
2869            }
2870        }
2871        if (isTopOfStackForClientToRemove) {
2872            // we removed an entry at the top of the stack:
2873            //  notify the new top of the stack it gained focus.
2874            notifyTopOfAudioFocusStack();
2875            // there's a new top of the stack, let the remote control know
2876            synchronized(mRCStack) {
2877                checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
2878            }
2879        }
2880    }
2881
2882    /**
2883     * Helper function:
2884     * Returns true if the system is in a state where the focus can be reevaluated, false otherwise.
2885     */
2886    private boolean canReassignAudioFocus() {
2887        // focus requests are rejected during a phone call or when the phone is ringing
2888        // this is equivalent to IN_VOICE_COMM_FOCUS_ID having the focus
2889        if (!mFocusStack.isEmpty() && IN_VOICE_COMM_FOCUS_ID.equals(mFocusStack.peek().mClientId)) {
2890            return false;
2891        }
2892        return true;
2893    }
2894
2895    /**
2896     * Inner class to monitor audio focus client deaths, and remove them from the audio focus
2897     * stack if necessary.
2898     */
2899    private class AudioFocusDeathHandler implements IBinder.DeathRecipient {
2900        private IBinder mCb; // To be notified of client's death
2901
2902        AudioFocusDeathHandler(IBinder cb) {
2903            mCb = cb;
2904        }
2905
2906        public void binderDied() {
2907            synchronized(mAudioFocusLock) {
2908                Log.w(TAG, "  AudioFocus   audio focus client died");
2909                removeFocusStackEntryForClient(mCb);
2910            }
2911        }
2912
2913        public IBinder getBinder() {
2914            return mCb;
2915        }
2916    }
2917
2918
2919    /** @see AudioManager#requestAudioFocus(IAudioFocusDispatcher, int, int) */
2920    public int requestAudioFocus(int mainStreamType, int focusChangeHint, IBinder cb,
2921            IAudioFocusDispatcher fd, String clientId, String callingPackageName) {
2922        Log.i(TAG, " AudioFocus  requestAudioFocus() from " + clientId);
2923        // the main stream type for the audio focus request is currently not used. It may
2924        // potentially be used to handle multiple stream type-dependent audio focuses.
2925
2926        // we need a valid binder callback for clients
2927        if (!cb.pingBinder()) {
2928            Log.e(TAG, " AudioFocus DOA client for requestAudioFocus(), aborting.");
2929            return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
2930        }
2931
2932        synchronized(mAudioFocusLock) {
2933            if (!canReassignAudioFocus()) {
2934                return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
2935            }
2936
2937            // handle the potential premature death of the new holder of the focus
2938            // (premature death == death before abandoning focus)
2939            // Register for client death notification
2940            AudioFocusDeathHandler afdh = new AudioFocusDeathHandler(cb);
2941            try {
2942                cb.linkToDeath(afdh, 0);
2943            } catch (RemoteException e) {
2944                // client has already died!
2945                Log.w(TAG, "AudioFocus  requestAudioFocus() could not link to "+cb+" binder death");
2946                return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
2947            }
2948
2949            if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientId)) {
2950                // if focus is already owned by this client and the reason for acquiring the focus
2951                // hasn't changed, don't do anything
2952                if (mFocusStack.peek().mFocusChangeType == focusChangeHint) {
2953                    // unlink death handler so it can be gc'ed.
2954                    // linkToDeath() creates a JNI global reference preventing collection.
2955                    cb.unlinkToDeath(afdh, 0);
2956                    return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
2957                }
2958                // the reason for the audio focus request has changed: remove the current top of
2959                // stack and respond as if we had a new focus owner
2960                FocusStackEntry fse = mFocusStack.pop();
2961                fse.unlinkToDeath();
2962            }
2963
2964            // notify current top of stack it is losing focus
2965            if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) {
2966                try {
2967                    mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange(
2968                            -1 * focusChangeHint, // loss and gain codes are inverse of each other
2969                            mFocusStack.peek().mClientId);
2970                } catch (RemoteException e) {
2971                    Log.e(TAG, " Failure to signal loss of focus due to "+ e);
2972                    e.printStackTrace();
2973                }
2974            }
2975
2976            // focus requester might already be somewhere below in the stack, remove it
2977            removeFocusStackEntry(clientId, false /* signal */);
2978
2979            // push focus requester at the top of the audio focus stack
2980            mFocusStack.push(new FocusStackEntry(mainStreamType, focusChangeHint, fd, cb,
2981                    clientId, afdh, callingPackageName, Binder.getCallingUid()));
2982
2983            // there's a new top of the stack, let the remote control know
2984            synchronized(mRCStack) {
2985                checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
2986            }
2987        }//synchronized(mAudioFocusLock)
2988
2989        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
2990    }
2991
2992    /** @see AudioManager#abandonAudioFocus(IAudioFocusDispatcher) */
2993    public int abandonAudioFocus(IAudioFocusDispatcher fl, String clientId) {
2994        Log.i(TAG, " AudioFocus  abandonAudioFocus() from " + clientId);
2995        try {
2996            // this will take care of notifying the new focus owner if needed
2997            synchronized(mAudioFocusLock) {
2998                removeFocusStackEntry(clientId, true);
2999            }
3000        } catch (java.util.ConcurrentModificationException cme) {
3001            // Catching this exception here is temporary. It is here just to prevent
3002            // a crash seen when the "Silent" notification is played. This is believed to be fixed
3003            // but this try catch block is left just to be safe.
3004            Log.e(TAG, "FATAL EXCEPTION AudioFocus  abandonAudioFocus() caused " + cme);
3005            cme.printStackTrace();
3006        }
3007
3008        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
3009    }
3010
3011
3012    public void unregisterAudioFocusClient(String clientId) {
3013        synchronized(mAudioFocusLock) {
3014            removeFocusStackEntry(clientId, false);
3015        }
3016    }
3017
3018
3019    //==========================================================================================
3020    // RemoteControl
3021    //==========================================================================================
3022    /**
3023     * Receiver for media button intents. Handles the dispatching of the media button event
3024     * to one of the registered listeners, or if there was none, resumes the intent broadcast
3025     * to the rest of the system.
3026     */
3027    private class MediaButtonBroadcastReceiver extends BroadcastReceiver {
3028        @Override
3029        public void onReceive(Context context, Intent intent) {
3030            String action = intent.getAction();
3031            if (!Intent.ACTION_MEDIA_BUTTON.equals(action)) {
3032                return;
3033            }
3034            KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
3035            if (event != null) {
3036                // if in a call or ringing, do not break the current phone app behavior
3037                // TODO modify this to let the phone app specifically get the RC focus
3038                //      add modify the phone app to take advantage of the new API
3039                synchronized(mRingingLock) {
3040                    if (mIsRinging || (getMode() == AudioSystem.MODE_IN_CALL) ||
3041                            (getMode() == AudioSystem.MODE_IN_COMMUNICATION) ||
3042                            (getMode() == AudioSystem.MODE_RINGTONE) ) {
3043                        return;
3044                    }
3045                }
3046                synchronized(mRCStack) {
3047                    if (!mRCStack.empty()) {
3048                        // create a new intent to fill in the extras of the registered PendingIntent
3049                        Intent targetedIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
3050                        Bundle extras = intent.getExtras();
3051                        if (extras != null) {
3052                            targetedIntent.putExtras(extras);
3053                            // trap the current broadcast
3054                            abortBroadcast();
3055                            //Log.v(TAG, " Sending intent" + targetedIntent);
3056                            // send the intent that was registered by the client
3057                            try {
3058                                mRCStack.peek().mMediaIntent.send(context, 0, targetedIntent);
3059                            } catch (CanceledException e) {
3060                                Log.e(TAG, "Error sending pending intent " + mRCStack.peek());
3061                                e.printStackTrace();
3062                            }
3063                        }
3064                    }
3065                }
3066            }
3067        }
3068    }
3069
3070    private final Object mCurrentRcLock = new Object();
3071    /**
3072     * The one remote control client which will receive a request for display information.
3073     * This object may be null.
3074     * Access protected by mCurrentRcLock.
3075     */
3076    private IRemoteControlClient mCurrentRcClient = null;
3077
3078    private final static int RC_INFO_NONE = 0;
3079    private final static int RC_INFO_ALL =
3080        RemoteControlClient.FLAG_INFORMATION_REQUEST_ALBUM_ART |
3081        RemoteControlClient.FLAG_INFORMATION_REQUEST_KEY_MEDIA |
3082        RemoteControlClient.FLAG_INFORMATION_REQUEST_METADATA |
3083        RemoteControlClient.FLAG_INFORMATION_REQUEST_PLAYSTATE;
3084
3085    /**
3086     * A monotonically increasing generation counter for mCurrentRcClient.
3087     * Only accessed with a lock on mCurrentRcLock.
3088     * No value wrap-around issues as we only act on equal values.
3089     */
3090    private int mCurrentRcClientGen = 0;
3091
3092    /**
3093     * Inner class to monitor remote control client deaths, and remove the client for the
3094     * remote control stack if necessary.
3095     */
3096    private class RcClientDeathHandler implements IBinder.DeathRecipient {
3097        private IBinder mCb; // To be notified of client's death
3098        private PendingIntent mMediaIntent;
3099
3100        RcClientDeathHandler(IBinder cb, PendingIntent pi) {
3101            mCb = cb;
3102            mMediaIntent = pi;
3103        }
3104
3105        public void binderDied() {
3106            Log.w(TAG, "  RemoteControlClient died");
3107            // remote control client died, make sure the displays don't use it anymore
3108            //  by setting its remote control client to null
3109            registerRemoteControlClient(mMediaIntent, null/*rcClient*/, null/*ignored*/);
3110        }
3111
3112        public IBinder getBinder() {
3113            return mCb;
3114        }
3115    }
3116
3117    private static class RemoteControlStackEntry {
3118        /**
3119         * The target for the ACTION_MEDIA_BUTTON events.
3120         * Always non null.
3121         */
3122        public PendingIntent mMediaIntent;
3123        /**
3124         * The registered media button event receiver.
3125         * Always non null.
3126         */
3127        public ComponentName mReceiverComponent;
3128        public String mCallingPackageName;
3129        public int mCallingUid;
3130        /**
3131         * Provides access to the information to display on the remote control.
3132         * May be null (when a media button event receiver is registered,
3133         *     but no remote control client has been registered) */
3134        public IRemoteControlClient mRcClient;
3135        public RcClientDeathHandler mRcClientDeathHandler;
3136
3137        /** precondition: mediaIntent != null, eventReceiver != null */
3138        public RemoteControlStackEntry(PendingIntent mediaIntent, ComponentName eventReceiver) {
3139            mMediaIntent = mediaIntent;
3140            mReceiverComponent = eventReceiver;
3141            mCallingUid = -1;
3142            mRcClient = null;
3143        }
3144
3145        public void unlinkToRcClientDeath() {
3146            if ((mRcClientDeathHandler != null) && (mRcClientDeathHandler.mCb != null)) {
3147                try {
3148                    mRcClientDeathHandler.mCb.unlinkToDeath(mRcClientDeathHandler, 0);
3149                    mRcClientDeathHandler = null;
3150                } catch (java.util.NoSuchElementException e) {
3151                    // not much we can do here
3152                    Log.e(TAG, "Encountered " + e + " in unlinkToRcClientDeath()");
3153                    e.printStackTrace();
3154                }
3155            }
3156        }
3157
3158        @Override
3159        protected void finalize() throws Throwable {
3160            unlinkToRcClientDeath();// unlink exception handled inside method
3161            super.finalize();
3162        }
3163    }
3164
3165    /**
3166     *  The stack of remote control event receivers.
3167     *  Code sections and methods that modify the remote control event receiver stack are
3168     *  synchronized on mRCStack, but also BEFORE on mFocusLock as any change in either
3169     *  stack, audio focus or RC, can lead to a change in the remote control display
3170     */
3171    private Stack<RemoteControlStackEntry> mRCStack = new Stack<RemoteControlStackEntry>();
3172
3173    /**
3174     * Helper function:
3175     * Display in the log the current entries in the remote control focus stack
3176     */
3177    private void dumpRCStack(PrintWriter pw) {
3178        pw.println("\nRemote Control stack entries:");
3179        synchronized(mRCStack) {
3180            Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3181            while(stackIterator.hasNext()) {
3182                RemoteControlStackEntry rcse = stackIterator.next();
3183                pw.println("  pi: " + rcse.mMediaIntent +
3184                        "  -- ercvr: " + rcse.mReceiverComponent +
3185                        "  -- client: " + rcse.mRcClient +
3186                        "  -- uid: " + rcse.mCallingUid);
3187            }
3188        }
3189    }
3190
3191    /**
3192     * Helper function:
3193     * Remove any entry in the remote control stack that has the same package name as packageName
3194     * Pre-condition: packageName != null
3195     */
3196    private void removeMediaButtonReceiverForPackage(String packageName) {
3197        synchronized(mRCStack) {
3198            if (mRCStack.empty()) {
3199                return;
3200            } else {
3201                RemoteControlStackEntry oldTop = mRCStack.peek();
3202                Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3203                // iterate over the stack entries
3204                while(stackIterator.hasNext()) {
3205                    RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
3206                    if (packageName.equalsIgnoreCase(rcse.mReceiverComponent.getPackageName())) {
3207                        // a stack entry is from the package being removed, remove it from the stack
3208                        stackIterator.remove();
3209                        rcse.unlinkToRcClientDeath();
3210                    }
3211                }
3212                if (mRCStack.empty()) {
3213                    // no saved media button receiver
3214                    mAudioHandler.sendMessage(
3215                            mAudioHandler.obtainMessage(MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0,
3216                                    null));
3217                } else if (oldTop != mRCStack.peek()) {
3218                    // the top of the stack has changed, save it in the system settings
3219                    // by posting a message to persist it
3220                    mAudioHandler.sendMessage(
3221                            mAudioHandler.obtainMessage(MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0,
3222                                    mRCStack.peek().mReceiverComponent));
3223                }
3224            }
3225        }
3226    }
3227
3228    /**
3229     * Helper function:
3230     * Restore remote control receiver from the system settings.
3231     */
3232    private void restoreMediaButtonReceiver() {
3233        String receiverName = Settings.System.getString(mContentResolver,
3234                Settings.System.MEDIA_BUTTON_RECEIVER);
3235        if ((null != receiverName) && !receiverName.isEmpty()) {
3236            ComponentName eventReceiver = ComponentName.unflattenFromString(receiverName);
3237            // construct a PendingIntent targeted to the restored component name
3238            // for the media button and register it
3239            Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
3240            //     the associated intent will be handled by the component being registered
3241            mediaButtonIntent.setComponent(eventReceiver);
3242            PendingIntent pi = PendingIntent.getBroadcast(mContext,
3243                    0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/);
3244            registerMediaButtonIntent(pi, eventReceiver);
3245        }
3246    }
3247
3248    /**
3249     * Helper function:
3250     * Set the new remote control receiver at the top of the RC focus stack.
3251     * precondition: mediaIntent != null, target != null
3252     */
3253    private void pushMediaButtonReceiver(PendingIntent mediaIntent, ComponentName target) {
3254        // already at top of stack?
3255        if (!mRCStack.empty() && mRCStack.peek().mMediaIntent.equals(mediaIntent)) {
3256            return;
3257        }
3258        Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3259        RemoteControlStackEntry rcse = null;
3260        boolean wasInsideStack = false;
3261        while(stackIterator.hasNext()) {
3262            rcse = (RemoteControlStackEntry)stackIterator.next();
3263            if(rcse.mMediaIntent.equals(mediaIntent)) {
3264                wasInsideStack = true;
3265                stackIterator.remove();
3266                break;
3267            }
3268        }
3269        if (!wasInsideStack) {
3270            rcse = new RemoteControlStackEntry(mediaIntent, target);
3271        }
3272        mRCStack.push(rcse);
3273
3274        // post message to persist the default media button receiver
3275        mAudioHandler.sendMessage( mAudioHandler.obtainMessage(
3276                MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0, target/*obj*/) );
3277    }
3278
3279    /**
3280     * Helper function:
3281     * Remove the remote control receiver from the RC focus stack.
3282     * precondition: pi != null
3283     */
3284    private void removeMediaButtonReceiver(PendingIntent pi) {
3285        Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3286        while(stackIterator.hasNext()) {
3287            RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
3288            if(rcse.mMediaIntent.equals(pi)) {
3289                stackIterator.remove();
3290                rcse.unlinkToRcClientDeath();
3291                break;
3292            }
3293        }
3294    }
3295
3296    /**
3297     * Helper function:
3298     * Called synchronized on mRCStack
3299     */
3300    private boolean isCurrentRcController(PendingIntent pi) {
3301        if (!mRCStack.empty() && mRCStack.peek().mMediaIntent.equals(pi)) {
3302            return true;
3303        }
3304        return false;
3305    }
3306
3307    //==========================================================================================
3308    // Remote control display / client
3309    //==========================================================================================
3310    /**
3311     * Update the remote control displays with the new "focused" client generation
3312     */
3313    private void setNewRcClientOnDisplays_syncRcsCurrc(int newClientGeneration,
3314            PendingIntent newMediaIntent, boolean clearing) {
3315        // NOTE: Only one IRemoteControlDisplay supported in this implementation
3316        if (mRcDisplay != null) {
3317            try {
3318                mRcDisplay.setCurrentClientId(
3319                        newClientGeneration, newMediaIntent, clearing);
3320            } catch (RemoteException e) {
3321                Log.e(TAG, "Dead display in setNewRcClientOnDisplays_syncRcsCurrc() "+e);
3322                // if we had a display before, stop monitoring its death
3323                rcDisplay_stopDeathMonitor_syncRcStack();
3324                mRcDisplay = null;
3325            }
3326        }
3327    }
3328
3329    /**
3330     * Update the remote control clients with the new "focused" client generation
3331     */
3332    private void setNewRcClientGenerationOnClients_syncRcsCurrc(int newClientGeneration) {
3333        Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3334        while(stackIterator.hasNext()) {
3335            RemoteControlStackEntry se = stackIterator.next();
3336            if ((se != null) && (se.mRcClient != null)) {
3337                try {
3338                    se.mRcClient.setCurrentClientGenerationId(newClientGeneration);
3339                } catch (RemoteException e) {
3340                    Log.w(TAG, "Dead client in setNewRcClientGenerationOnClients_syncRcsCurrc()"+e);
3341                    stackIterator.remove();
3342                    se.unlinkToRcClientDeath();
3343                }
3344            }
3345        }
3346    }
3347
3348    /**
3349     * Update the displays and clients with the new "focused" client generation and name
3350     * @param newClientGeneration the new generation value matching a client update
3351     * @param newClientEventReceiver the media button event receiver associated with the client.
3352     *    May be null, which implies there is no registered media button event receiver.
3353     * @param clearing true if the new client generation value maps to a remote control update
3354     *    where the display should be cleared.
3355     */
3356    private void setNewRcClient_syncRcsCurrc(int newClientGeneration,
3357            PendingIntent newMediaIntent, boolean clearing) {
3358        // send the new valid client generation ID to all displays
3359        setNewRcClientOnDisplays_syncRcsCurrc(newClientGeneration, newMediaIntent, clearing);
3360        // send the new valid client generation ID to all clients
3361        setNewRcClientGenerationOnClients_syncRcsCurrc(newClientGeneration);
3362    }
3363
3364    /**
3365     * Called when processing MSG_RCDISPLAY_CLEAR event
3366     */
3367    private void onRcDisplayClear() {
3368        if (DEBUG_RC) Log.i(TAG, "Clear remote control display");
3369
3370        synchronized(mRCStack) {
3371            synchronized(mCurrentRcLock) {
3372                mCurrentRcClientGen++;
3373                // synchronously update the displays and clients with the new client generation
3374                setNewRcClient_syncRcsCurrc(mCurrentRcClientGen,
3375                        null /*newMediaIntent*/, true /*clearing*/);
3376            }
3377        }
3378    }
3379
3380    /**
3381     * Called when processing MSG_RCDISPLAY_UPDATE event
3382     */
3383    private void onRcDisplayUpdate(RemoteControlStackEntry rcse, int flags /* USED ?*/) {
3384        synchronized(mRCStack) {
3385            synchronized(mCurrentRcLock) {
3386                if ((mCurrentRcClient != null) && (mCurrentRcClient.equals(rcse.mRcClient))) {
3387                    if (DEBUG_RC) Log.i(TAG, "Display/update remote control ");
3388
3389                    mCurrentRcClientGen++;
3390                    // synchronously update the displays and clients with
3391                    //      the new client generation
3392                    setNewRcClient_syncRcsCurrc(mCurrentRcClientGen,
3393                            rcse.mMediaIntent /*newMediaIntent*/,
3394                            false /*clearing*/);
3395
3396                    // tell the current client that it needs to send info
3397                    try {
3398                        mCurrentRcClient.onInformationRequested(mCurrentRcClientGen,
3399                                flags, mArtworkExpectedWidth, mArtworkExpectedHeight);
3400                    } catch (RemoteException e) {
3401                        Log.e(TAG, "Current valid remote client is dead: "+e);
3402                        mCurrentRcClient = null;
3403                    }
3404                } else {
3405                    // the remote control display owner has changed between the
3406                    // the message to update the display was sent, and the time it
3407                    // gets to be processed (now)
3408                }
3409            }
3410        }
3411    }
3412
3413
3414    /**
3415     * Helper function:
3416     * Called synchronized on mRCStack
3417     */
3418    private void clearRemoteControlDisplay_syncAfRcs() {
3419        synchronized(mCurrentRcLock) {
3420            mCurrentRcClient = null;
3421        }
3422        // will cause onRcDisplayClear() to be called in AudioService's handler thread
3423        mAudioHandler.sendMessage( mAudioHandler.obtainMessage(MSG_RCDISPLAY_CLEAR) );
3424    }
3425
3426    /**
3427     * Helper function for code readability: only to be called from
3428     *    checkUpdateRemoteControlDisplay_syncAfRcs() which checks the preconditions for
3429     *    this method.
3430     * Preconditions:
3431     *    - called synchronized mAudioFocusLock then on mRCStack
3432     *    - mRCStack.isEmpty() is false
3433     */
3434    private void updateRemoteControlDisplay_syncAfRcs(int infoChangedFlags) {
3435        RemoteControlStackEntry rcse = mRCStack.peek();
3436        int infoFlagsAboutToBeUsed = infoChangedFlags;
3437        // this is where we enforce opt-in for information display on the remote controls
3438        //   with the new AudioManager.registerRemoteControlClient() API
3439        if (rcse.mRcClient == null) {
3440            //Log.w(TAG, "Can't update remote control display with null remote control client");
3441            clearRemoteControlDisplay_syncAfRcs();
3442            return;
3443        }
3444        synchronized(mCurrentRcLock) {
3445            if (!rcse.mRcClient.equals(mCurrentRcClient)) {
3446                // new RC client, assume every type of information shall be queried
3447                infoFlagsAboutToBeUsed = RC_INFO_ALL;
3448            }
3449            mCurrentRcClient = rcse.mRcClient;
3450        }
3451        // will cause onRcDisplayUpdate() to be called in AudioService's handler thread
3452        mAudioHandler.sendMessage( mAudioHandler.obtainMessage(MSG_RCDISPLAY_UPDATE,
3453                infoFlagsAboutToBeUsed /* arg1 */, 0, rcse /* obj, != null */) );
3454    }
3455
3456    /**
3457     * Helper function:
3458     * Called synchronized on mAudioFocusLock, then mRCStack
3459     * Check whether the remote control display should be updated, triggers the update if required
3460     * @param infoChangedFlags the flags corresponding to the remote control client information
3461     *     that has changed, if applicable (checking for the update conditions might trigger a
3462     *     clear, rather than an update event).
3463     */
3464    private void checkUpdateRemoteControlDisplay_syncAfRcs(int infoChangedFlags) {
3465        // determine whether the remote control display should be refreshed
3466        // if either stack is empty, there is a mismatch, so clear the RC display
3467        if (mRCStack.isEmpty() || mFocusStack.isEmpty()) {
3468            clearRemoteControlDisplay_syncAfRcs();
3469            return;
3470        }
3471        // if the top of the two stacks belong to different packages, there is a mismatch, clear
3472        if ((mRCStack.peek().mCallingPackageName != null)
3473                && (mFocusStack.peek().mPackageName != null)
3474                && !(mRCStack.peek().mCallingPackageName.compareTo(
3475                        mFocusStack.peek().mPackageName) == 0)) {
3476            clearRemoteControlDisplay_syncAfRcs();
3477            return;
3478        }
3479        // if the audio focus didn't originate from the same Uid as the one in which the remote
3480        //   control information will be retrieved, clear
3481        if (mRCStack.peek().mCallingUid != mFocusStack.peek().mCallingUid) {
3482            clearRemoteControlDisplay_syncAfRcs();
3483            return;
3484        }
3485        // refresh conditions were verified: update the remote controls
3486        // ok to call: synchronized mAudioFocusLock then on mRCStack, mRCStack is not empty
3487        updateRemoteControlDisplay_syncAfRcs(infoChangedFlags);
3488    }
3489
3490    /**
3491     * see AudioManager.registerMediaButtonIntent(PendingIntent pi, ComponentName c)
3492     * precondition: mediaIntent != null, target != null
3493     */
3494    public void registerMediaButtonIntent(PendingIntent mediaIntent, ComponentName eventReceiver) {
3495        Log.i(TAG, "  Remote Control   registerMediaButtonIntent() for " + mediaIntent);
3496
3497        synchronized(mAudioFocusLock) {
3498            synchronized(mRCStack) {
3499                pushMediaButtonReceiver(mediaIntent, eventReceiver);
3500                // new RC client, assume every type of information shall be queried
3501                checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
3502            }
3503        }
3504    }
3505
3506    /**
3507     * see AudioManager.unregisterMediaButtonIntent(PendingIntent mediaIntent)
3508     * precondition: mediaIntent != null, eventReceiver != null
3509     */
3510    public void unregisterMediaButtonIntent(PendingIntent mediaIntent, ComponentName eventReceiver)
3511    {
3512        Log.i(TAG, "  Remote Control   unregisterMediaButtonIntent() for " + mediaIntent);
3513
3514        synchronized(mAudioFocusLock) {
3515            synchronized(mRCStack) {
3516                boolean topOfStackWillChange = isCurrentRcController(mediaIntent);
3517                removeMediaButtonReceiver(mediaIntent);
3518                if (topOfStackWillChange) {
3519                    // current RC client will change, assume every type of info needs to be queried
3520                    checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
3521                }
3522            }
3523        }
3524    }
3525
3526    /**
3527     * see AudioManager.registerRemoteControlClient(ComponentName eventReceiver, ...)
3528     * Note: using this method with rcClient == null is a way to "disable" the IRemoteControlClient
3529     *     without modifying the RC stack, but while still causing the display to refresh (will
3530     *     become blank as a result of this)
3531     */
3532    public void registerRemoteControlClient(PendingIntent mediaIntent,
3533            IRemoteControlClient rcClient, String callingPackageName) {
3534        if (DEBUG_RC) Log.i(TAG, "Register remote control client rcClient="+rcClient);
3535        synchronized(mAudioFocusLock) {
3536            synchronized(mRCStack) {
3537                // store the new display information
3538                Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3539                while(stackIterator.hasNext()) {
3540                    RemoteControlStackEntry rcse = stackIterator.next();
3541                    if(rcse.mMediaIntent.equals(mediaIntent)) {
3542                        // already had a remote control client?
3543                        if (rcse.mRcClientDeathHandler != null) {
3544                            // stop monitoring the old client's death
3545                            rcse.unlinkToRcClientDeath();
3546                        }
3547                        // save the new remote control client
3548                        rcse.mRcClient = rcClient;
3549                        rcse.mCallingPackageName = callingPackageName;
3550                        rcse.mCallingUid = Binder.getCallingUid();
3551                        if (rcClient == null) {
3552                            // here rcse.mRcClientDeathHandler is null;
3553                            break;
3554                        }
3555
3556                        // there is a new (non-null) client:
3557                        // 1/ give the new client the current display (if any)
3558                        if (mRcDisplay != null) {
3559                            try {
3560                                rcse.mRcClient.plugRemoteControlDisplay(mRcDisplay);
3561                            } catch (RemoteException e) {
3562                                Log.e(TAG, "Error connecting remote control display to client: "+e);
3563                                e.printStackTrace();
3564                            }
3565                        }
3566                        // 2/ monitor the new client's death
3567                        IBinder b = rcse.mRcClient.asBinder();
3568                        RcClientDeathHandler rcdh =
3569                                new RcClientDeathHandler(b, rcse.mMediaIntent);
3570                        try {
3571                            b.linkToDeath(rcdh, 0);
3572                        } catch (RemoteException e) {
3573                            // remote control client is DOA, disqualify it
3574                            Log.w(TAG, "registerRemoteControlClient() has a dead client " + b);
3575                            rcse.mRcClient = null;
3576                        }
3577                        rcse.mRcClientDeathHandler = rcdh;
3578                        break;
3579                    }
3580                }
3581                // if the eventReceiver is at the top of the stack
3582                // then check for potential refresh of the remote controls
3583                if (isCurrentRcController(mediaIntent)) {
3584                    checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
3585                }
3586            }
3587        }
3588    }
3589
3590    /**
3591     * see AudioManager.unregisterRemoteControlClient(PendingIntent pi, ...)
3592     * rcClient is guaranteed non-null
3593     */
3594    public void unregisterRemoteControlClient(PendingIntent mediaIntent,
3595            IRemoteControlClient rcClient) {
3596        synchronized(mAudioFocusLock) {
3597            synchronized(mRCStack) {
3598                Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3599                while(stackIterator.hasNext()) {
3600                    RemoteControlStackEntry rcse = stackIterator.next();
3601                    if ((rcse.mMediaIntent.equals(mediaIntent))
3602                            && rcClient.equals(rcse.mRcClient)) {
3603                        // we found the IRemoteControlClient to unregister
3604                        // stop monitoring its death
3605                        rcse.unlinkToRcClientDeath();
3606                        // reset the client-related fields
3607                        rcse.mRcClient = null;
3608                        rcse.mCallingPackageName = null;
3609                    }
3610                }
3611            }
3612        }
3613    }
3614
3615    /**
3616     * The remote control displays.
3617     * Access synchronized on mRCStack
3618     * NOTE: Only one IRemoteControlDisplay supported in this implementation
3619     */
3620    private IRemoteControlDisplay mRcDisplay;
3621    private RcDisplayDeathHandler mRcDisplayDeathHandler;
3622    private int mArtworkExpectedWidth = -1;
3623    private int mArtworkExpectedHeight = -1;
3624    /**
3625     * Inner class to monitor remote control display deaths, and unregister them from the list
3626     * of displays if necessary.
3627     */
3628    private class RcDisplayDeathHandler implements IBinder.DeathRecipient {
3629        private IBinder mCb; // To be notified of client's death
3630
3631        public RcDisplayDeathHandler(IBinder b) {
3632            if (DEBUG_RC) Log.i(TAG, "new RcDisplayDeathHandler for "+b);
3633            mCb = b;
3634        }
3635
3636        public void binderDied() {
3637            synchronized(mRCStack) {
3638                Log.w(TAG, "RemoteControl: display died");
3639                mRcDisplay = null;
3640            }
3641        }
3642
3643        public void unlinkToRcDisplayDeath() {
3644            if (DEBUG_RC) Log.i(TAG, "unlinkToRcDisplayDeath for "+mCb);
3645            try {
3646                mCb.unlinkToDeath(this, 0);
3647            } catch (java.util.NoSuchElementException e) {
3648                // not much we can do here, the display was being unregistered anyway
3649                Log.e(TAG, "Encountered " + e + " in unlinkToRcDisplayDeath()");
3650                e.printStackTrace();
3651            }
3652        }
3653
3654    }
3655
3656    private void rcDisplay_stopDeathMonitor_syncRcStack() {
3657        if (mRcDisplay != null) { // implies (mRcDisplayDeathHandler != null)
3658            // we had a display before, stop monitoring its death
3659            mRcDisplayDeathHandler.unlinkToRcDisplayDeath();
3660        }
3661    }
3662
3663    private void rcDisplay_startDeathMonitor_syncRcStack() {
3664        if (mRcDisplay != null) {
3665            // new non-null display, monitor its death
3666            IBinder b = mRcDisplay.asBinder();
3667            mRcDisplayDeathHandler = new RcDisplayDeathHandler(b);
3668            try {
3669                b.linkToDeath(mRcDisplayDeathHandler, 0);
3670            } catch (RemoteException e) {
3671                // remote control display is DOA, disqualify it
3672                Log.w(TAG, "registerRemoteControlDisplay() has a dead client " + b);
3673                mRcDisplay = null;
3674            }
3675        }
3676    }
3677
3678    /**
3679     * Register an IRemoteControlDisplay.
3680     * Notify all IRemoteControlClient of the new display and cause the RemoteControlClient
3681     * at the top of the stack to update the new display with its information.
3682     * Since only one IRemoteControlDisplay is supported, this will unregister the previous display.
3683     * @param rcd the IRemoteControlDisplay to register. No effect if null.
3684     */
3685    public void registerRemoteControlDisplay(IRemoteControlDisplay rcd) {
3686        if (DEBUG_RC) Log.d(TAG, ">>> registerRemoteControlDisplay("+rcd+")");
3687        synchronized(mAudioFocusLock) {
3688            synchronized(mRCStack) {
3689                if ((mRcDisplay == rcd) || (rcd == null)) {
3690                    return;
3691                }
3692                // if we had a display before, stop monitoring its death
3693                rcDisplay_stopDeathMonitor_syncRcStack();
3694                mRcDisplay = rcd;
3695                // new display, start monitoring its death
3696                rcDisplay_startDeathMonitor_syncRcStack();
3697
3698                // let all the remote control clients there is a new display
3699                // no need to unplug the previous because we only support one display
3700                // and the clients don't track the death of the display
3701                Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3702                while(stackIterator.hasNext()) {
3703                    RemoteControlStackEntry rcse = stackIterator.next();
3704                    if(rcse.mRcClient != null) {
3705                        try {
3706                            rcse.mRcClient.plugRemoteControlDisplay(mRcDisplay);
3707                        } catch (RemoteException e) {
3708                            Log.e(TAG, "Error connecting remote control display to client: " + e);
3709                            e.printStackTrace();
3710                        }
3711                    }
3712                }
3713
3714                // we have a new display, of which all the clients are now aware: have it be updated
3715                checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL);
3716            }
3717        }
3718    }
3719
3720    /**
3721     * Unregister an IRemoteControlDisplay.
3722     * Since only one IRemoteControlDisplay is supported, this has no effect if the one to
3723     *    unregister is not the current one.
3724     * @param rcd the IRemoteControlDisplay to unregister. No effect if null.
3725     */
3726    public void unregisterRemoteControlDisplay(IRemoteControlDisplay rcd) {
3727        if (DEBUG_RC) Log.d(TAG, "<<< unregisterRemoteControlDisplay("+rcd+")");
3728        synchronized(mRCStack) {
3729            // only one display here, so you can only unregister the current display
3730            if ((rcd == null) || (rcd != mRcDisplay)) {
3731                if (DEBUG_RC) Log.w(TAG, "    trying to unregister unregistered RCD");
3732                return;
3733            }
3734            // if we had a display before, stop monitoring its death
3735            rcDisplay_stopDeathMonitor_syncRcStack();
3736            mRcDisplay = null;
3737
3738            // disconnect this remote control display from all the clients
3739            Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
3740            while(stackIterator.hasNext()) {
3741                RemoteControlStackEntry rcse = stackIterator.next();
3742                if(rcse.mRcClient != null) {
3743                    try {
3744                        rcse.mRcClient.unplugRemoteControlDisplay(rcd);
3745                    } catch (RemoteException e) {
3746                        Log.e(TAG, "Error disconnecting remote control display to client: " + e);
3747                        e.printStackTrace();
3748                    }
3749                }
3750            }
3751        }
3752    }
3753
3754    public void remoteControlDisplayUsesBitmapSize(IRemoteControlDisplay rcd, int w, int h) {
3755        synchronized(mRCStack) {
3756            // NOTE: Only one IRemoteControlDisplay supported in this implementation
3757            mArtworkExpectedWidth = w;
3758            mArtworkExpectedHeight = h;
3759        }
3760    }
3761
3762    @Override
3763    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3764        // TODO probably a lot more to do here than just the audio focus and remote control stacks
3765        dumpFocusStack(pw);
3766        dumpRCStack(pw);
3767    }
3768
3769
3770}
3771