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