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