AudioService.java revision 30d181690e48b26cdfae3b144d23f1e16c75da37
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.util.ArrayList;
59import java.util.HashMap;
60import java.util.Iterator;
61import java.util.List;
62import java.util.Map;
63import java.util.NoSuchElementException;
64import java.util.Set;
65import java.util.Stack;
66
67/**
68 * The implementation of the volume manager service.
69 * <p>
70 * This implementation focuses on delivering a responsive UI. Most methods are
71 * asynchronous to external calls. For example, the task of setting a volume
72 * will update our internal state, but in a separate thread will set the system
73 * volume and later persist to the database. Similarly, setting the ringer mode
74 * will update the state and broadcast a change and in a separate thread later
75 * persist the ringer mode.
76 *
77 * @hide
78 */
79public class AudioService extends IAudioService.Stub {
80
81    private static final String TAG = "AudioService";
82
83    /** How long to delay before persisting a change in volume/ringer mode. */
84    private static final int PERSIST_DELAY = 3000;
85
86    private Context mContext;
87    private ContentResolver mContentResolver;
88
89
90    /** The UI */
91    private VolumePanel mVolumePanel;
92
93    // sendMsg() flags
94    /** Used when a message should be shared across all stream types. */
95    private static final int SHARED_MSG = -1;
96    /** If the msg is already queued, replace it with this one. */
97    private static final int SENDMSG_REPLACE = 0;
98    /** If the msg is already queued, ignore this one and leave the old. */
99    private static final int SENDMSG_NOOP = 1;
100    /** If the msg is already queued, queue this one and leave the old. */
101    private static final int SENDMSG_QUEUE = 2;
102
103    // AudioHandler message.whats
104    private static final int MSG_SET_SYSTEM_VOLUME = 0;
105    private static final int MSG_PERSIST_VOLUME = 1;
106    private static final int MSG_PERSIST_RINGER_MODE = 3;
107    private static final int MSG_PERSIST_VIBRATE_SETTING = 4;
108    private static final int MSG_MEDIA_SERVER_DIED = 5;
109    private static final int MSG_MEDIA_SERVER_STARTED = 6;
110    private static final int MSG_PLAY_SOUND_EFFECT = 7;
111    private static final int MSG_BTA2DP_DOCK_TIMEOUT = 8;
112
113    private static final int BTA2DP_DOCK_TIMEOUT_MILLIS = 8000;
114
115    /** @see AudioSystemThread */
116    private AudioSystemThread mAudioSystemThread;
117    /** @see AudioHandler */
118    private AudioHandler mAudioHandler;
119    /** @see VolumeStreamState */
120    private VolumeStreamState[] mStreamStates;
121    private SettingsObserver mSettingsObserver;
122
123    private int mMode;
124    private Object mSettingsLock = new Object();
125    private boolean mMediaServerOk;
126
127    private SoundPool mSoundPool;
128    private Object mSoundEffectsLock = new Object();
129    private static final int NUM_SOUNDPOOL_CHANNELS = 4;
130    private static final int SOUND_EFFECT_VOLUME = 1000;
131
132    /* Sound effect file names  */
133    private static final String SOUND_EFFECTS_PATH = "/media/audio/ui/";
134    private static final String[] SOUND_EFFECT_FILES = new String[] {
135        "Effect_Tick.ogg",
136        "KeypressStandard.ogg",
137        "KeypressSpacebar.ogg",
138        "KeypressDelete.ogg",
139        "KeypressReturn.ogg"
140    };
141
142    /* Sound effect file name mapping sound effect id (AudioManager.FX_xxx) to
143     * file index in SOUND_EFFECT_FILES[] (first column) and indicating if effect
144     * uses soundpool (second column) */
145    private int[][] SOUND_EFFECT_FILES_MAP = new int[][] {
146        {0, -1},  // FX_KEY_CLICK
147        {0, -1},  // FX_FOCUS_NAVIGATION_UP
148        {0, -1},  // FX_FOCUS_NAVIGATION_DOWN
149        {0, -1},  // FX_FOCUS_NAVIGATION_LEFT
150        {0, -1},  // FX_FOCUS_NAVIGATION_RIGHT
151        {1, -1},  // FX_KEYPRESS_STANDARD
152        {2, -1},  // FX_KEYPRESS_SPACEBAR
153        {3, -1},  // FX_FOCUS_DELETE
154        {4, -1}   // FX_FOCUS_RETURN
155    };
156
157   /** @hide Maximum volume index values for audio streams */
158    private int[] MAX_STREAM_VOLUME = new int[] {
159        5,  // STREAM_VOICE_CALL
160        7,  // STREAM_SYSTEM
161        7,  // STREAM_RING
162        15, // STREAM_MUSIC
163        7,  // STREAM_ALARM
164        7,  // STREAM_NOTIFICATION
165        15, // STREAM_BLUETOOTH_SCO
166        7,  // STREAM_SYSTEM_ENFORCED
167        15, // STREAM_DTMF
168        15  // STREAM_TTS
169    };
170    /* STREAM_VOLUME_ALIAS[] indicates for each stream if it uses the volume settings
171     * of another stream: This avoids multiplying the volume settings for hidden
172     * stream types that follow other stream behavior for volume settings
173     * NOTE: do not create loops in aliases! */
174    private int[] STREAM_VOLUME_ALIAS = new int[] {
175        AudioSystem.STREAM_VOICE_CALL,  // STREAM_VOICE_CALL
176        AudioSystem.STREAM_SYSTEM,  // STREAM_SYSTEM
177        AudioSystem.STREAM_RING,  // STREAM_RING
178        AudioSystem.STREAM_MUSIC, // STREAM_MUSIC
179        AudioSystem.STREAM_ALARM,  // STREAM_ALARM
180        AudioSystem.STREAM_NOTIFICATION,  // STREAM_NOTIFICATION
181        AudioSystem.STREAM_BLUETOOTH_SCO, // STREAM_BLUETOOTH_SCO
182        AudioSystem.STREAM_SYSTEM,  // STREAM_SYSTEM_ENFORCED
183        AudioSystem.STREAM_VOICE_CALL, // STREAM_DTMF
184        AudioSystem.STREAM_MUSIC  // STREAM_TTS
185    };
186
187    private AudioSystem.ErrorCallback mAudioSystemCallback = new AudioSystem.ErrorCallback() {
188        public void onError(int error) {
189            switch (error) {
190            case AudioSystem.AUDIO_STATUS_SERVER_DIED:
191                if (mMediaServerOk) {
192                    sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
193                            null, 1500);
194                    mMediaServerOk = false;
195                }
196                break;
197            case AudioSystem.AUDIO_STATUS_OK:
198                if (!mMediaServerOk) {
199                    sendMsg(mAudioHandler, MSG_MEDIA_SERVER_STARTED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
200                            null, 0);
201                    mMediaServerOk = true;
202                }
203                break;
204            default:
205                break;
206            }
207       }
208    };
209
210    /**
211     * Current ringer mode from one of {@link AudioManager#RINGER_MODE_NORMAL},
212     * {@link AudioManager#RINGER_MODE_SILENT}, or
213     * {@link AudioManager#RINGER_MODE_VIBRATE}.
214     */
215    private int mRingerMode;
216
217    /** @see System#MODE_RINGER_STREAMS_AFFECTED */
218    private int mRingerModeAffectedStreams;
219
220    // Streams currently muted by ringer mode
221    private int mRingerModeMutedStreams;
222
223    /** @see System#MUTE_STREAMS_AFFECTED */
224    private int mMuteAffectedStreams;
225
226    /**
227     * Has multiple bits per vibrate type to indicate the type's vibrate
228     * setting. See {@link #setVibrateSetting(int, int)}.
229     * <p>
230     * NOTE: This is not the final decision of whether vibrate is on/off for the
231     * type since it depends on the ringer mode. See {@link #shouldVibrate(int)}.
232     */
233    private int mVibrateSetting;
234
235    /** @see System#NOTIFICATIONS_USE_RING_VOLUME */
236    private int mNotificationsUseRingVolume;
237
238    // Broadcast receiver for device connections intent broadcasts
239    private final BroadcastReceiver mReceiver = new AudioServiceBroadcastReceiver();
240
241    //  Broadcast receiver for media button broadcasts (separate from mReceiver to
242    //  independently change its priority)
243    private final BroadcastReceiver mMediaButtonReceiver = new MediaButtonBroadcastReceiver();
244
245    // Used to alter media button redirection when the phone is ringing.
246    private boolean mIsRinging = false;
247
248    // Devices currently connected
249    private HashMap <Integer, String> mConnectedDevices = new HashMap <Integer, String>();
250
251    // Forced device usage for communications
252    private int mForcedUseForComm;
253
254    // List of binder death handlers for setMode() client processes.
255    // The last process to have called setMode() is at the top of the list.
256    private ArrayList <SetModeDeathHandler> mSetModeDeathHandlers = new ArrayList <SetModeDeathHandler>();
257
258    // List of clients having issued a SCO start request
259    private ArrayList <ScoClient> mScoClients = new ArrayList <ScoClient>();
260
261    // BluetoothHeadset API to control SCO connection
262    private BluetoothHeadset mBluetoothHeadset;
263
264    // Bluetooth headset device
265    private BluetoothDevice mBluetoothHeadsetDevice;
266
267    ///////////////////////////////////////////////////////////////////////////
268    // Construction
269    ///////////////////////////////////////////////////////////////////////////
270
271    /** @hide */
272    public AudioService(Context context) {
273        mContext = context;
274        mContentResolver = context.getContentResolver();
275
276       // Intialized volume
277        MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = SystemProperties.getInt(
278            "ro.config.vc_call_vol_steps",
279           MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]);
280
281        mVolumePanel = new VolumePanel(context, this);
282        mSettingsObserver = new SettingsObserver();
283        mForcedUseForComm = AudioSystem.FORCE_NONE;
284        createAudioSystemThread();
285        readPersistedSettings();
286        createStreamStates();
287        // Call setMode() to initialize mSetModeDeathHandlers
288        mMode = AudioSystem.MODE_INVALID;
289        setMode(AudioSystem.MODE_NORMAL, null);
290        mMediaServerOk = true;
291
292        // Call setRingerModeInt() to apply correct mute
293        // state on streams affected by ringer mode.
294        mRingerModeMutedStreams = 0;
295        setRingerModeInt(getRingerMode(), false);
296
297        AudioSystem.setErrorCallback(mAudioSystemCallback);
298        loadSoundEffects();
299
300        mBluetoothHeadsetDevice = null;
301        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
302        if (adapter != null) {
303            adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
304                                    BluetoothProfile.HEADSET);
305        }
306
307        // Register for device connection intent broadcasts.
308        IntentFilter intentFilter =
309                new IntentFilter(Intent.ACTION_HEADSET_PLUG);
310
311        intentFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
312        intentFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
313        intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
314        intentFilter.addAction(Intent.ACTION_DOCK_EVENT);
315        intentFilter.addAction(Intent.ACTION_USB_ANLG_HEADSET_PLUG);
316        intentFilter.addAction(Intent.ACTION_USB_DGTL_HEADSET_PLUG);
317        context.registerReceiver(mReceiver, intentFilter);
318
319        // Register for media button intent broadcasts.
320        intentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
321        intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
322        context.registerReceiver(mMediaButtonReceiver, intentFilter);
323
324        // Register for phone state monitoring
325        TelephonyManager tmgr = (TelephonyManager)
326                context.getSystemService(Context.TELEPHONY_SERVICE);
327        tmgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
328    }
329
330    private void createAudioSystemThread() {
331        mAudioSystemThread = new AudioSystemThread();
332        mAudioSystemThread.start();
333        waitForAudioHandlerCreation();
334    }
335
336    /** Waits for the volume handler to be created by the other thread. */
337    private void waitForAudioHandlerCreation() {
338        synchronized(this) {
339            while (mAudioHandler == null) {
340                try {
341                    // Wait for mAudioHandler to be set by the other thread
342                    wait();
343                } catch (InterruptedException e) {
344                    Log.e(TAG, "Interrupted while waiting on volume handler.");
345                }
346            }
347        }
348    }
349
350    private void createStreamStates() {
351        int numStreamTypes = AudioSystem.getNumStreamTypes();
352        VolumeStreamState[] streams = mStreamStates = new VolumeStreamState[numStreamTypes];
353
354        for (int i = 0; i < numStreamTypes; i++) {
355            streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[i]], i);
356        }
357
358        // Correct stream index values for streams with aliases
359        for (int i = 0; i < numStreamTypes; i++) {
360            if (STREAM_VOLUME_ALIAS[i] != i) {
361                int index = rescaleIndex(streams[i].mIndex, STREAM_VOLUME_ALIAS[i], i);
362                streams[i].mIndex = streams[i].getValidIndex(index);
363                setStreamVolumeIndex(i, index);
364                index = rescaleIndex(streams[i].mLastAudibleIndex, STREAM_VOLUME_ALIAS[i], i);
365                streams[i].mLastAudibleIndex = streams[i].getValidIndex(index);
366            }
367        }
368    }
369
370    private void readPersistedSettings() {
371        final ContentResolver cr = mContentResolver;
372
373        mRingerMode = System.getInt(cr, System.MODE_RINGER, AudioManager.RINGER_MODE_NORMAL);
374
375        mVibrateSetting = System.getInt(cr, System.VIBRATE_ON, 0);
376
377        mRingerModeAffectedStreams = Settings.System.getInt(cr,
378                Settings.System.MODE_RINGER_STREAMS_AFFECTED,
379                ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)|
380                 (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED)));
381
382        mMuteAffectedStreams = System.getInt(cr,
383                System.MUTE_STREAMS_AFFECTED,
384                ((1 << AudioSystem.STREAM_MUSIC)|(1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_SYSTEM)));
385
386        mNotificationsUseRingVolume = System.getInt(cr,
387                Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 1);
388
389        if (mNotificationsUseRingVolume == 1) {
390            STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING;
391        }
392        // Each stream will read its own persisted settings
393
394        // Broadcast the sticky intent
395        broadcastRingerMode();
396
397        // Broadcast vibrate settings
398        broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);
399        broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION);
400    }
401
402    private void setStreamVolumeIndex(int stream, int index) {
403        AudioSystem.setStreamVolumeIndex(stream, (index + 5)/10);
404    }
405
406    private int rescaleIndex(int index, int srcStream, int dstStream) {
407        return (index * mStreamStates[dstStream].getMaxIndex() + mStreamStates[srcStream].getMaxIndex() / 2) / mStreamStates[srcStream].getMaxIndex();
408    }
409
410    ///////////////////////////////////////////////////////////////////////////
411    // IPC methods
412    ///////////////////////////////////////////////////////////////////////////
413
414    /** @see AudioManager#adjustVolume(int, int) */
415    public void adjustVolume(int direction, int flags) {
416        adjustSuggestedStreamVolume(direction, AudioManager.USE_DEFAULT_STREAM_TYPE, flags);
417    }
418
419    /** @see AudioManager#adjustVolume(int, int, int) */
420    public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) {
421
422        int streamType = getActiveStreamType(suggestedStreamType);
423
424        // Don't play sound on other streams
425        if (streamType != AudioSystem.STREAM_RING && (flags & AudioManager.FLAG_PLAY_SOUND) != 0) {
426            flags &= ~AudioManager.FLAG_PLAY_SOUND;
427        }
428
429        adjustStreamVolume(streamType, direction, flags);
430    }
431
432    /** @see AudioManager#adjustStreamVolume(int, int, int) */
433    public void adjustStreamVolume(int streamType, int direction, int flags) {
434        ensureValidDirection(direction);
435        ensureValidStreamType(streamType);
436
437
438        VolumeStreamState streamState = mStreamStates[STREAM_VOLUME_ALIAS[streamType]];
439        final int oldIndex = (streamState.muteCount() != 0) ? streamState.mLastAudibleIndex : streamState.mIndex;
440        boolean adjustVolume = true;
441
442        // If either the client forces allowing ringer modes for this adjustment,
443        // or the stream type is one that is affected by ringer modes
444        if ((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0
445                || streamType == AudioSystem.STREAM_RING) {
446            // Check if the ringer mode changes with this volume adjustment. If
447            // it does, it will handle adjusting the volume, so we won't below
448            adjustVolume = checkForRingerModeChange(oldIndex, direction);
449        }
450
451        // If stream is muted, adjust last audible index only
452        int index;
453        if (streamState.muteCount() != 0) {
454            if (adjustVolume) {
455                streamState.adjustLastAudibleIndex(direction);
456                // Post a persist volume msg
457                sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamType,
458                        SENDMSG_REPLACE, 0, 1, streamState, PERSIST_DELAY);
459            }
460            index = streamState.mLastAudibleIndex;
461        } else {
462            if (adjustVolume && streamState.adjustIndex(direction)) {
463                // Post message to set system volume (it in turn will post a message
464                // to persist). Do not change volume if stream is muted.
465                sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, STREAM_VOLUME_ALIAS[streamType], SENDMSG_NOOP, 0, 0,
466                        streamState, 0);
467            }
468            index = streamState.mIndex;
469        }
470        // UI
471        mVolumePanel.postVolumeChanged(streamType, flags);
472        // Broadcast Intent
473        sendVolumeUpdate(streamType, oldIndex, index);
474    }
475
476    /** @see AudioManager#setStreamVolume(int, int, int) */
477    public void setStreamVolume(int streamType, int index, int flags) {
478        ensureValidStreamType(streamType);
479        VolumeStreamState streamState = mStreamStates[STREAM_VOLUME_ALIAS[streamType]];
480
481        final int oldIndex = (streamState.muteCount() != 0) ? streamState.mLastAudibleIndex : streamState.mIndex;
482
483        index = rescaleIndex(index * 10, streamType, STREAM_VOLUME_ALIAS[streamType]);
484        setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, false, true);
485
486        index = (streamState.muteCount() != 0) ? streamState.mLastAudibleIndex : streamState.mIndex;
487
488        // UI, etc.
489        mVolumePanel.postVolumeChanged(streamType, flags);
490        // Broadcast Intent
491        sendVolumeUpdate(streamType, oldIndex, index);
492    }
493
494    private void sendVolumeUpdate(int streamType, int oldIndex, int index) {
495        oldIndex = (oldIndex + 5) / 10;
496        index = (index + 5) / 10;
497
498        Intent intent = new Intent(AudioManager.VOLUME_CHANGED_ACTION);
499        intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, streamType);
500        intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, index);
501        intent.putExtra(AudioManager.EXTRA_PREV_VOLUME_STREAM_VALUE, oldIndex);
502
503        mContext.sendBroadcast(intent);
504    }
505
506    /**
507     * Sets the stream state's index, and posts a message to set system volume.
508     * This will not call out to the UI. Assumes a valid stream type.
509     *
510     * @param streamType Type of the stream
511     * @param index Desired volume index of the stream
512     * @param force If true, set the volume even if the desired volume is same
513     * as the current volume.
514     * @param lastAudible If true, stores new index as last audible one
515     */
516    private void setStreamVolumeInt(int streamType, int index, boolean force, boolean lastAudible) {
517        VolumeStreamState streamState = mStreamStates[streamType];
518
519        // If stream is muted, set last audible index only
520        if (streamState.muteCount() != 0) {
521            // Do not allow last audible index to be 0
522            if (index != 0) {
523                streamState.setLastAudibleIndex(index);
524                // Post a persist volume msg
525                sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamType,
526                        SENDMSG_REPLACE, 0, 1, streamState, PERSIST_DELAY);
527            }
528        } else {
529            if (streamState.setIndex(index, lastAudible) || force) {
530                // Post message to set system volume (it in turn will post a message
531                // to persist).
532                sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, streamType, SENDMSG_NOOP, 0, 0,
533                        streamState, 0);
534            }
535        }
536    }
537
538    /** @see AudioManager#setStreamSolo(int, boolean) */
539    public void setStreamSolo(int streamType, boolean state, IBinder cb) {
540        for (int stream = 0; stream < mStreamStates.length; stream++) {
541            if (!isStreamAffectedByMute(stream) || stream == streamType) continue;
542            // Bring back last audible volume
543            mStreamStates[stream].mute(cb, state);
544         }
545    }
546
547    /** @see AudioManager#setStreamMute(int, boolean) */
548    public void setStreamMute(int streamType, boolean state, IBinder cb) {
549        if (isStreamAffectedByMute(streamType)) {
550            mStreamStates[streamType].mute(cb, state);
551        }
552    }
553
554    /** @see AudioManager#getStreamVolume(int) */
555    public int getStreamVolume(int streamType) {
556        ensureValidStreamType(streamType);
557        return (mStreamStates[streamType].mIndex + 5) / 10;
558    }
559
560    /** @see AudioManager#getStreamMaxVolume(int) */
561    public int getStreamMaxVolume(int streamType) {
562        ensureValidStreamType(streamType);
563        return (mStreamStates[streamType].getMaxIndex() + 5) / 10;
564    }
565
566    /** @see AudioManager#getRingerMode() */
567    public int getRingerMode() {
568        return mRingerMode;
569    }
570
571    /** @see AudioManager#setRingerMode(int) */
572    public void setRingerMode(int ringerMode) {
573        synchronized (mSettingsLock) {
574            if (ringerMode != mRingerMode) {
575                setRingerModeInt(ringerMode, true);
576                // Send sticky broadcast
577                broadcastRingerMode();
578            }
579        }
580    }
581
582    private void setRingerModeInt(int ringerMode, boolean persist) {
583        mRingerMode = ringerMode;
584
585        // Mute stream if not previously muted by ringer mode and ringer mode
586        // is not RINGER_MODE_NORMAL and stream is affected by ringer mode.
587        // Unmute stream if previously muted by ringer mode and ringer mode
588        // is RINGER_MODE_NORMAL or stream is not affected by ringer mode.
589        int numStreamTypes = AudioSystem.getNumStreamTypes();
590        for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
591            if (isStreamMutedByRingerMode(streamType)) {
592                if (!isStreamAffectedByRingerMode(streamType) ||
593                    mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
594                    mStreamStates[streamType].mute(null, false);
595                    mRingerModeMutedStreams &= ~(1 << streamType);
596                }
597            } else {
598                if (isStreamAffectedByRingerMode(streamType) &&
599                    mRingerMode != AudioManager.RINGER_MODE_NORMAL) {
600                   mStreamStates[streamType].mute(null, true);
601                   mRingerModeMutedStreams |= (1 << streamType);
602               }
603            }
604        }
605
606        // Post a persist ringer mode msg
607        if (persist) {
608            sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE, SHARED_MSG,
609                    SENDMSG_REPLACE, 0, 0, null, PERSIST_DELAY);
610        }
611    }
612
613    /** @see AudioManager#shouldVibrate(int) */
614    public boolean shouldVibrate(int vibrateType) {
615
616        switch (getVibrateSetting(vibrateType)) {
617
618            case AudioManager.VIBRATE_SETTING_ON:
619                return mRingerMode != AudioManager.RINGER_MODE_SILENT;
620
621            case AudioManager.VIBRATE_SETTING_ONLY_SILENT:
622                return mRingerMode == AudioManager.RINGER_MODE_VIBRATE;
623
624            case AudioManager.VIBRATE_SETTING_OFF:
625                // return false, even for incoming calls
626                return false;
627
628            default:
629                return false;
630        }
631    }
632
633    /** @see AudioManager#getVibrateSetting(int) */
634    public int getVibrateSetting(int vibrateType) {
635        return (mVibrateSetting >> (vibrateType * 2)) & 3;
636    }
637
638    /** @see AudioManager#setVibrateSetting(int, int) */
639    public void setVibrateSetting(int vibrateType, int vibrateSetting) {
640
641        mVibrateSetting = getValueForVibrateSetting(mVibrateSetting, vibrateType, vibrateSetting);
642
643        // Broadcast change
644        broadcastVibrateSetting(vibrateType);
645
646        // Post message to set ringer mode (it in turn will post a message
647        // to persist)
648        sendMsg(mAudioHandler, MSG_PERSIST_VIBRATE_SETTING, SHARED_MSG, SENDMSG_NOOP, 0, 0,
649                null, 0);
650    }
651
652    /**
653     * @see #setVibrateSetting(int, int)
654     */
655    public static int getValueForVibrateSetting(int existingValue, int vibrateType,
656            int vibrateSetting) {
657
658        // First clear the existing setting. Each vibrate type has two bits in
659        // the value. Note '3' is '11' in binary.
660        existingValue &= ~(3 << (vibrateType * 2));
661
662        // Set into the old value
663        existingValue |= (vibrateSetting & 3) << (vibrateType * 2);
664
665        return existingValue;
666    }
667
668    private class SetModeDeathHandler implements IBinder.DeathRecipient {
669        private IBinder mCb; // To be notified of client's death
670        private int mMode = AudioSystem.MODE_NORMAL; // Current mode set by this client
671
672        SetModeDeathHandler(IBinder cb) {
673            mCb = cb;
674        }
675
676        public void binderDied() {
677            synchronized(mSetModeDeathHandlers) {
678                Log.w(TAG, "setMode() client died");
679                int index = mSetModeDeathHandlers.indexOf(this);
680                if (index < 0) {
681                    Log.w(TAG, "unregistered setMode() client died");
682                } else {
683                    mSetModeDeathHandlers.remove(this);
684                    // If dead client was a the top of client list,
685                    // apply next mode in the stack
686                    if (index == 0) {
687                        // mSetModeDeathHandlers is never empty as the initial entry
688                        // created when AudioService starts is never removed
689                        SetModeDeathHandler hdlr = mSetModeDeathHandlers.get(0);
690                        int mode = hdlr.getMode();
691                        if (AudioService.this.mMode != mode) {
692                            if (AudioSystem.setPhoneState(mode) == AudioSystem.AUDIO_STATUS_OK) {
693                                AudioService.this.mMode = mode;
694                            }
695                        }
696                    }
697                }
698            }
699        }
700
701        public void setMode(int mode) {
702            mMode = mode;
703        }
704
705        public int getMode() {
706            return mMode;
707        }
708
709        public IBinder getBinder() {
710            return mCb;
711        }
712    }
713
714    /** @see AudioManager#setMode(int) */
715    public void setMode(int mode, IBinder cb) {
716        if (!checkAudioSettingsPermission("setMode()")) {
717            return;
718        }
719
720        if (mode < AudioSystem.MODE_CURRENT || mode > AudioSystem.MODE_IN_CALL) {
721            return;
722        }
723
724        synchronized (mSettingsLock) {
725            if (mode == AudioSystem.MODE_CURRENT) {
726                mode = mMode;
727            }
728            if (mode != mMode) {
729                if (AudioSystem.setPhoneState(mode) == AudioSystem.AUDIO_STATUS_OK) {
730                    mMode = mode;
731
732                    synchronized(mSetModeDeathHandlers) {
733                        SetModeDeathHandler hdlr = null;
734                        Iterator iter = mSetModeDeathHandlers.iterator();
735                        while (iter.hasNext()) {
736                            SetModeDeathHandler h = (SetModeDeathHandler)iter.next();
737                            if (h.getBinder() == cb) {
738                                hdlr = h;
739                                // Remove from client list so that it is re-inserted at top of list
740                                iter.remove();
741                                break;
742                            }
743                        }
744                        if (hdlr == null) {
745                            hdlr = new SetModeDeathHandler(cb);
746                            // cb is null when setMode() is called by AudioService constructor
747                            if (cb != null) {
748                                // Register for client death notification
749                                try {
750                                    cb.linkToDeath(hdlr, 0);
751                                } catch (RemoteException e) {
752                                    // Client has died!
753                                    Log.w(TAG, "setMode() could not link to "+cb+" binder death");
754                                }
755                            }
756                        }
757                        // Last client to call setMode() is always at top of client list
758                        // as required by SetModeDeathHandler.binderDied()
759                        mSetModeDeathHandlers.add(0, hdlr);
760                        hdlr.setMode(mode);
761                    }
762
763                    if (mode != AudioSystem.MODE_NORMAL) {
764                        clearAllScoClients();
765                    }
766                }
767            }
768            int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
769            int index = mStreamStates[STREAM_VOLUME_ALIAS[streamType]].mIndex;
770            setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, true, false);
771        }
772    }
773
774    /** @see AudioManager#getMode() */
775    public int getMode() {
776        return mMode;
777    }
778
779    /** @see AudioManager#playSoundEffect(int) */
780    public void playSoundEffect(int effectType) {
781        sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP,
782                effectType, -1, null, 0);
783    }
784
785    /** @see AudioManager#playSoundEffect(int, float) */
786    public void playSoundEffectVolume(int effectType, float volume) {
787        loadSoundEffects();
788        sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP,
789                effectType, (int) (volume * 1000), null, 0);
790    }
791
792    /**
793     * Loads samples into the soundpool.
794     * This method must be called at when sound effects are enabled
795     */
796    public boolean loadSoundEffects() {
797        synchronized (mSoundEffectsLock) {
798            if (mSoundPool != null) {
799                return true;
800            }
801            mSoundPool = new SoundPool(NUM_SOUNDPOOL_CHANNELS, AudioSystem.STREAM_SYSTEM, 0);
802            if (mSoundPool == null) {
803                return false;
804            }
805            /*
806             * poolId table: The value -1 in this table indicates that corresponding
807             * file (same index in SOUND_EFFECT_FILES[] has not been loaded.
808             * Once loaded, the value in poolId is the sample ID and the same
809             * sample can be reused for another effect using the same file.
810             */
811            int[] poolId = new int[SOUND_EFFECT_FILES.length];
812            for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) {
813                poolId[fileIdx] = -1;
814            }
815            /*
816             * Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded.
817             * If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0:
818             * this indicates we have a valid sample loaded for this effect.
819             */
820            for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
821                // Do not load sample if this effect uses the MediaPlayer
822                if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) {
823                    continue;
824                }
825                if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) {
826                    String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effect][0]];
827                    int sampleId = mSoundPool.load(filePath, 0);
828                    SOUND_EFFECT_FILES_MAP[effect][1] = sampleId;
829                    poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId;
830                    if (sampleId <= 0) {
831                        Log.w(TAG, "Soundpool could not load file: "+filePath);
832                    }
833                } else {
834                    SOUND_EFFECT_FILES_MAP[effect][1] = poolId[SOUND_EFFECT_FILES_MAP[effect][0]];
835                }
836            }
837        }
838
839        return true;
840    }
841
842    /**
843     *  Unloads samples from the sound pool.
844     *  This method can be called to free some memory when
845     *  sound effects are disabled.
846     */
847    public void unloadSoundEffects() {
848        synchronized (mSoundEffectsLock) {
849            if (mSoundPool == null) {
850                return;
851            }
852            int[] poolId = new int[SOUND_EFFECT_FILES.length];
853            for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) {
854                poolId[fileIdx] = 0;
855            }
856
857            for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
858                if (SOUND_EFFECT_FILES_MAP[effect][1] <= 0) {
859                    continue;
860                }
861                if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == 0) {
862                    mSoundPool.unload(SOUND_EFFECT_FILES_MAP[effect][1]);
863                    SOUND_EFFECT_FILES_MAP[effect][1] = -1;
864                    poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1;
865                }
866            }
867            mSoundPool = null;
868        }
869    }
870
871    /** @see AudioManager#reloadAudioSettings() */
872    public void reloadAudioSettings() {
873        // restore ringer mode, ringer mode affected streams, mute affected streams and vibrate settings
874        readPersistedSettings();
875
876        // restore volume settings
877        int numStreamTypes = AudioSystem.getNumStreamTypes();
878        for (int streamType = 0; streamType < numStreamTypes; streamType++) {
879            VolumeStreamState streamState = mStreamStates[streamType];
880
881            String settingName = System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[streamType]];
882            String lastAudibleSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE;
883            int index = Settings.System.getInt(mContentResolver,
884                                           settingName,
885                                           AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
886            if (STREAM_VOLUME_ALIAS[streamType] != streamType) {
887                index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType);
888            } else {
889                index *= 10;
890            }
891            streamState.mIndex = streamState.getValidIndex(index);
892
893            index = (index + 5) / 10;
894            index = Settings.System.getInt(mContentResolver,
895                                            lastAudibleSettingName,
896                                            (index > 0) ? index : AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
897            if (STREAM_VOLUME_ALIAS[streamType] != streamType) {
898                index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType);
899            } else {
900                index *= 10;
901            }
902            streamState.mLastAudibleIndex = streamState.getValidIndex(index);
903
904            // unmute stream that was muted but is not affect by mute anymore
905            if (streamState.muteCount() != 0 && !isStreamAffectedByMute(streamType)) {
906                int size = streamState.mDeathHandlers.size();
907                for (int i = 0; i < size; i++) {
908                    streamState.mDeathHandlers.get(i).mMuteCount = 1;
909                    streamState.mDeathHandlers.get(i).mute(false);
910                }
911            }
912            // apply stream volume
913            if (streamState.muteCount() == 0) {
914                setStreamVolumeIndex(streamType, streamState.mIndex);
915            }
916        }
917
918        // apply new ringer mode
919        setRingerModeInt(getRingerMode(), false);
920    }
921
922    /** @see AudioManager#setSpeakerphoneOn() */
923    public void setSpeakerphoneOn(boolean on){
924        if (!checkAudioSettingsPermission("setSpeakerphoneOn()")) {
925            return;
926        }
927        if (on) {
928            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_SPEAKER);
929            mForcedUseForComm = AudioSystem.FORCE_SPEAKER;
930        } else {
931            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_NONE);
932            mForcedUseForComm = AudioSystem.FORCE_NONE;
933        }
934    }
935
936    /** @see AudioManager#isSpeakerphoneOn() */
937    public boolean isSpeakerphoneOn() {
938        if (mForcedUseForComm == AudioSystem.FORCE_SPEAKER) {
939            return true;
940        } else {
941            return false;
942        }
943    }
944
945    /** @see AudioManager#setBluetoothScoOn() */
946    public void setBluetoothScoOn(boolean on){
947        if (!checkAudioSettingsPermission("setBluetoothScoOn()")) {
948            return;
949        }
950        if (on) {
951            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_BT_SCO);
952            AudioSystem.setForceUse(AudioSystem.FOR_RECORD, AudioSystem.FORCE_BT_SCO);
953            mForcedUseForComm = AudioSystem.FORCE_BT_SCO;
954        } else {
955            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_NONE);
956            AudioSystem.setForceUse(AudioSystem.FOR_RECORD, AudioSystem.FORCE_NONE);
957            mForcedUseForComm = AudioSystem.FORCE_NONE;
958        }
959    }
960
961    /** @see AudioManager#isBluetoothScoOn() */
962    public boolean isBluetoothScoOn() {
963        if (mForcedUseForComm == AudioSystem.FORCE_BT_SCO) {
964            return true;
965        } else {
966            return false;
967        }
968    }
969
970    /** @see AudioManager#startBluetoothSco() */
971    public void startBluetoothSco(IBinder cb){
972        if (!checkAudioSettingsPermission("startBluetoothSco()")) {
973            return;
974        }
975        ScoClient client = getScoClient(cb);
976        client.incCount();
977    }
978
979    /** @see AudioManager#stopBluetoothSco() */
980    public void stopBluetoothSco(IBinder cb){
981        if (!checkAudioSettingsPermission("stopBluetoothSco()")) {
982            return;
983        }
984        ScoClient client = getScoClient(cb);
985        client.decCount();
986    }
987
988    private class ScoClient implements IBinder.DeathRecipient {
989        private IBinder mCb; // To be notified of client's death
990        private int mStartcount; // number of SCO connections started by this client
991
992        ScoClient(IBinder cb) {
993            mCb = cb;
994            mStartcount = 0;
995        }
996
997        public void binderDied() {
998            synchronized(mScoClients) {
999                Log.w(TAG, "SCO client died");
1000                int index = mScoClients.indexOf(this);
1001                if (index < 0) {
1002                    Log.w(TAG, "unregistered SCO client died");
1003                } else {
1004                    clearCount(true);
1005                    mScoClients.remove(this);
1006                }
1007            }
1008        }
1009
1010        public void incCount() {
1011            synchronized(mScoClients) {
1012                requestScoState(BluetoothHeadset.STATE_AUDIO_CONNECTED);
1013                if (mStartcount == 0) {
1014                    try {
1015                        mCb.linkToDeath(this, 0);
1016                    } catch (RemoteException e) {
1017                        // client has already died!
1018                        Log.w(TAG, "ScoClient  incCount() could not link to "+mCb+" binder death");
1019                    }
1020                }
1021                mStartcount++;
1022            }
1023        }
1024
1025        public void decCount() {
1026            synchronized(mScoClients) {
1027                if (mStartcount == 0) {
1028                    Log.w(TAG, "ScoClient.decCount() already 0");
1029                } else {
1030                    mStartcount--;
1031                    if (mStartcount == 0) {
1032                        try {
1033                            mCb.unlinkToDeath(this, 0);
1034                        } catch (NoSuchElementException e) {
1035                            Log.w(TAG, "decCount() going to 0 but not registered to binder");
1036                        }
1037                    }
1038                    requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
1039                }
1040            }
1041        }
1042
1043        public void clearCount(boolean stopSco) {
1044            synchronized(mScoClients) {
1045                if (mStartcount != 0) {
1046                    try {
1047                        mCb.unlinkToDeath(this, 0);
1048                    } catch (NoSuchElementException e) {
1049                        Log.w(TAG, "clearCount() mStartcount: "+mStartcount+" != 0 but not registered to binder");
1050                    }
1051                }
1052                mStartcount = 0;
1053                if (stopSco) {
1054                    requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
1055                }
1056            }
1057        }
1058
1059        public int getCount() {
1060            return mStartcount;
1061        }
1062
1063        public IBinder getBinder() {
1064            return mCb;
1065        }
1066
1067        public int totalCount() {
1068            synchronized(mScoClients) {
1069                int count = 0;
1070                int size = mScoClients.size();
1071                for (int i = 0; i < size; i++) {
1072                    count += mScoClients.get(i).getCount();
1073                }
1074                return count;
1075            }
1076        }
1077
1078        private void requestScoState(int state) {
1079            if (totalCount() == 0 &&
1080                mBluetoothHeadsetDevice != null &&
1081                AudioService.this.mMode == AudioSystem.MODE_NORMAL) {
1082                if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED) {
1083                    mBluetoothHeadset.startVoiceRecognition(mBluetoothHeadsetDevice);
1084                } else {
1085                    mBluetoothHeadset.stopVoiceRecognition(mBluetoothHeadsetDevice);
1086                }
1087            }
1088        }
1089    }
1090
1091    public ScoClient getScoClient(IBinder cb) {
1092        synchronized(mScoClients) {
1093            ScoClient client;
1094            int size = mScoClients.size();
1095            for (int i = 0; i < size; i++) {
1096                client = mScoClients.get(i);
1097                if (client.getBinder() == cb)
1098                    return client;
1099            }
1100            client = new ScoClient(cb);
1101            mScoClients.add(client);
1102            return client;
1103        }
1104    }
1105
1106    public void clearAllScoClients() {
1107        synchronized(mScoClients) {
1108            int size = mScoClients.size();
1109            for (int i = 0; i < size; i++) {
1110                mScoClients.get(i).clearCount(false);
1111            }
1112        }
1113    }
1114
1115    private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
1116        new BluetoothProfile.ServiceListener() {
1117        public void onServiceConnected(int profile, BluetoothProfile proxy) {
1118            mBluetoothHeadset = (BluetoothHeadset) proxy;
1119            List<BluetoothDevice> deviceList = mBluetoothHeadset.getConnectedDevices();
1120            if (deviceList.size() > 0) {
1121                mBluetoothHeadsetDevice = deviceList.get(0);
1122            } else {
1123                mBluetoothHeadsetDevice = null;
1124            }
1125        }
1126        public void onServiceDisconnected(int profile) {
1127            if (mBluetoothHeadset != null) {
1128                List<BluetoothDevice> devices = mBluetoothHeadset.getConnectedDevices();
1129                if (devices.size() == 0) {
1130                    mBluetoothHeadsetDevice = null;
1131                    clearAllScoClients();
1132                }
1133                mBluetoothHeadset = null;
1134            }
1135        }
1136    };
1137
1138    ///////////////////////////////////////////////////////////////////////////
1139    // Internal methods
1140    ///////////////////////////////////////////////////////////////////////////
1141
1142    /**
1143     * Checks if the adjustment should change ringer mode instead of just
1144     * adjusting volume. If so, this will set the proper ringer mode and volume
1145     * indices on the stream states.
1146     */
1147    private boolean checkForRingerModeChange(int oldIndex, int direction) {
1148        boolean adjustVolumeIndex = true;
1149        int newRingerMode = mRingerMode;
1150
1151        if (mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
1152            // audible mode, at the bottom of the scale
1153            if (direction == AudioManager.ADJUST_LOWER
1154                    && (oldIndex + 5) / 10 == 1) {
1155                // "silent mode", but which one?
1156                newRingerMode = System.getInt(mContentResolver, System.VIBRATE_IN_SILENT, 1) == 1
1157                    ? AudioManager.RINGER_MODE_VIBRATE
1158                    : AudioManager.RINGER_MODE_SILENT;
1159            }
1160        } else {
1161            if (direction == AudioManager.ADJUST_RAISE) {
1162                // exiting silent mode
1163                newRingerMode = AudioManager.RINGER_MODE_NORMAL;
1164            } else {
1165                // prevent last audible index to reach 0
1166                adjustVolumeIndex = false;
1167            }
1168        }
1169
1170        if (newRingerMode != mRingerMode) {
1171            setRingerMode(newRingerMode);
1172
1173            /*
1174             * If we are changing ringer modes, do not increment/decrement the
1175             * volume index. Instead, the handler for the message above will
1176             * take care of changing the index.
1177             */
1178            adjustVolumeIndex = false;
1179        }
1180
1181        return adjustVolumeIndex;
1182    }
1183
1184    public boolean isStreamAffectedByRingerMode(int streamType) {
1185        return (mRingerModeAffectedStreams & (1 << streamType)) != 0;
1186    }
1187
1188    private boolean isStreamMutedByRingerMode(int streamType) {
1189        return (mRingerModeMutedStreams & (1 << streamType)) != 0;
1190    }
1191
1192    public boolean isStreamAffectedByMute(int streamType) {
1193        return (mMuteAffectedStreams & (1 << streamType)) != 0;
1194    }
1195
1196    private void ensureValidDirection(int direction) {
1197        if (direction < AudioManager.ADJUST_LOWER || direction > AudioManager.ADJUST_RAISE) {
1198            throw new IllegalArgumentException("Bad direction " + direction);
1199        }
1200    }
1201
1202    private void ensureValidStreamType(int streamType) {
1203        if (streamType < 0 || streamType >= mStreamStates.length) {
1204            throw new IllegalArgumentException("Bad stream type " + streamType);
1205        }
1206    }
1207
1208    private int getActiveStreamType(int suggestedStreamType) {
1209        boolean isOffhook = false;
1210        try {
1211            ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
1212            if (phone != null) isOffhook = phone.isOffhook();
1213        } catch (RemoteException e) {
1214            Log.w(TAG, "Couldn't connect to phone service", e);
1215        }
1216
1217        if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION) == AudioSystem.FORCE_BT_SCO) {
1218            // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO...");
1219            return AudioSystem.STREAM_BLUETOOTH_SCO;
1220        } else if (isOffhook || AudioSystem.isStreamActive(AudioSystem.STREAM_VOICE_CALL)) {
1221            // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL...");
1222            return AudioSystem.STREAM_VOICE_CALL;
1223        } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC)) {
1224            // Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC...");
1225            return AudioSystem.STREAM_MUSIC;
1226        } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
1227            // Log.v(TAG, "getActiveStreamType: Forcing STREAM_RING...");
1228            return AudioSystem.STREAM_RING;
1229        } else {
1230            // Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType);
1231            return suggestedStreamType;
1232        }
1233    }
1234
1235    private void broadcastRingerMode() {
1236        // Send sticky broadcast
1237        Intent broadcast = new Intent(AudioManager.RINGER_MODE_CHANGED_ACTION);
1238        broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, mRingerMode);
1239        broadcast.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
1240                | Intent.FLAG_RECEIVER_REPLACE_PENDING);
1241        long origCallerIdentityToken = Binder.clearCallingIdentity();
1242        mContext.sendStickyBroadcast(broadcast);
1243        Binder.restoreCallingIdentity(origCallerIdentityToken);
1244    }
1245
1246    private void broadcastVibrateSetting(int vibrateType) {
1247        // Send broadcast
1248        if (ActivityManagerNative.isSystemReady()) {
1249            Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION);
1250            broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType);
1251            broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType));
1252            mContext.sendBroadcast(broadcast);
1253        }
1254    }
1255
1256    // Message helper methods
1257    private static int getMsg(int baseMsg, int streamType) {
1258        return (baseMsg & 0xffff) | streamType << 16;
1259    }
1260
1261    private static int getMsgBase(int msg) {
1262        return msg & 0xffff;
1263    }
1264
1265    private static void sendMsg(Handler handler, int baseMsg, int streamType,
1266            int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) {
1267        int msg = (streamType == SHARED_MSG) ? baseMsg : getMsg(baseMsg, streamType);
1268
1269        if (existingMsgPolicy == SENDMSG_REPLACE) {
1270            handler.removeMessages(msg);
1271        } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) {
1272            return;
1273        }
1274
1275        handler
1276                .sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delay);
1277    }
1278
1279    boolean checkAudioSettingsPermission(String method) {
1280        if (mContext.checkCallingOrSelfPermission("android.permission.MODIFY_AUDIO_SETTINGS")
1281                == PackageManager.PERMISSION_GRANTED) {
1282            return true;
1283        }
1284        String msg = "Audio Settings Permission Denial: " + method + " from pid="
1285                + Binder.getCallingPid()
1286                + ", uid=" + Binder.getCallingUid();
1287        Log.w(TAG, msg);
1288        return false;
1289    }
1290
1291
1292    ///////////////////////////////////////////////////////////////////////////
1293    // Inner classes
1294    ///////////////////////////////////////////////////////////////////////////
1295
1296    public class VolumeStreamState {
1297        private final int mStreamType;
1298
1299        private String mVolumeIndexSettingName;
1300        private String mLastAudibleVolumeIndexSettingName;
1301        private int mIndexMax;
1302        private int mIndex;
1303        private int mLastAudibleIndex;
1304        private ArrayList<VolumeDeathHandler> mDeathHandlers; //handles mute/solo requests client death
1305
1306        private VolumeStreamState(String settingName, int streamType) {
1307
1308            setVolumeIndexSettingName(settingName);
1309
1310            mStreamType = streamType;
1311
1312            final ContentResolver cr = mContentResolver;
1313            mIndexMax = MAX_STREAM_VOLUME[streamType];
1314            mIndex = Settings.System.getInt(cr,
1315                                            mVolumeIndexSettingName,
1316                                            AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1317            mLastAudibleIndex = Settings.System.getInt(cr,
1318                                                       mLastAudibleVolumeIndexSettingName,
1319                                                       (mIndex > 0) ? mIndex : AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1320            AudioSystem.initStreamVolume(streamType, 0, mIndexMax);
1321            mIndexMax *= 10;
1322            mIndex = getValidIndex(10 * mIndex);
1323            mLastAudibleIndex = getValidIndex(10 * mLastAudibleIndex);
1324            setStreamVolumeIndex(streamType, mIndex);
1325            mDeathHandlers = new ArrayList<VolumeDeathHandler>();
1326        }
1327
1328        public void setVolumeIndexSettingName(String settingName) {
1329            mVolumeIndexSettingName = settingName;
1330            mLastAudibleVolumeIndexSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE;
1331        }
1332
1333        public boolean adjustIndex(int deltaIndex) {
1334            return setIndex(mIndex + deltaIndex * 10, true);
1335        }
1336
1337        public boolean setIndex(int index, boolean lastAudible) {
1338            int oldIndex = mIndex;
1339            mIndex = getValidIndex(index);
1340
1341            if (oldIndex != mIndex) {
1342                if (lastAudible) {
1343                    mLastAudibleIndex = mIndex;
1344                }
1345                // Apply change to all streams using this one as alias
1346                int numStreamTypes = AudioSystem.getNumStreamTypes();
1347                for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
1348                    if (streamType != mStreamType && STREAM_VOLUME_ALIAS[streamType] == mStreamType) {
1349                        mStreamStates[streamType].setIndex(rescaleIndex(mIndex, mStreamType, streamType), lastAudible);
1350                    }
1351                }
1352                return true;
1353            } else {
1354                return false;
1355            }
1356        }
1357
1358        public void setLastAudibleIndex(int index) {
1359            mLastAudibleIndex = getValidIndex(index);
1360        }
1361
1362        public void adjustLastAudibleIndex(int deltaIndex) {
1363            setLastAudibleIndex(mLastAudibleIndex + deltaIndex * 10);
1364        }
1365
1366        public int getMaxIndex() {
1367            return mIndexMax;
1368        }
1369
1370        public void mute(IBinder cb, boolean state) {
1371            VolumeDeathHandler handler = getDeathHandler(cb, state);
1372            if (handler == null) {
1373                Log.e(TAG, "Could not get client death handler for stream: "+mStreamType);
1374                return;
1375            }
1376            handler.mute(state);
1377        }
1378
1379        private int getValidIndex(int index) {
1380            if (index < 0) {
1381                return 0;
1382            } else if (index > mIndexMax) {
1383                return mIndexMax;
1384            }
1385
1386            return index;
1387        }
1388
1389        private class VolumeDeathHandler implements IBinder.DeathRecipient {
1390            private IBinder mICallback; // To be notified of client's death
1391            private int mMuteCount; // Number of active mutes for this client
1392
1393            VolumeDeathHandler(IBinder cb) {
1394                mICallback = cb;
1395            }
1396
1397            public void mute(boolean state) {
1398                synchronized(mDeathHandlers) {
1399                    if (state) {
1400                        if (mMuteCount == 0) {
1401                            // Register for client death notification
1402                            try {
1403                                // mICallback can be 0 if muted by AudioService
1404                                if (mICallback != null) {
1405                                    mICallback.linkToDeath(this, 0);
1406                                }
1407                                mDeathHandlers.add(this);
1408                                // If the stream is not yet muted by any client, set lvel to 0
1409                                if (muteCount() == 0) {
1410                                    setIndex(0, false);
1411                                    sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0,
1412                                            VolumeStreamState.this, 0);
1413                                }
1414                            } catch (RemoteException e) {
1415                                // Client has died!
1416                                binderDied();
1417                                mDeathHandlers.notify();
1418                                return;
1419                            }
1420                        } else {
1421                            Log.w(TAG, "stream: "+mStreamType+" was already muted by this client");
1422                        }
1423                        mMuteCount++;
1424                    } else {
1425                        if (mMuteCount == 0) {
1426                            Log.e(TAG, "unexpected unmute for stream: "+mStreamType);
1427                        } else {
1428                            mMuteCount--;
1429                            if (mMuteCount == 0) {
1430                                // Unregistr from client death notification
1431                                mDeathHandlers.remove(this);
1432                                // mICallback can be 0 if muted by AudioService
1433                                if (mICallback != null) {
1434                                    mICallback.unlinkToDeath(this, 0);
1435                                }
1436                                if (muteCount() == 0) {
1437                                    // If the stream is not muted any more, restore it's volume if
1438                                    // ringer mode allows it
1439                                    if (!isStreamAffectedByRingerMode(mStreamType) || mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
1440                                        setIndex(mLastAudibleIndex, false);
1441                                        sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0,
1442                                                VolumeStreamState.this, 0);
1443                                    }
1444                                }
1445                            }
1446                        }
1447                    }
1448                    mDeathHandlers.notify();
1449                }
1450            }
1451
1452            public void binderDied() {
1453                Log.w(TAG, "Volume service client died for stream: "+mStreamType);
1454                if (mMuteCount != 0) {
1455                    // Reset all active mute requests from this client.
1456                    mMuteCount = 1;
1457                    mute(false);
1458                }
1459            }
1460        }
1461
1462        private int muteCount() {
1463            int count = 0;
1464            int size = mDeathHandlers.size();
1465            for (int i = 0; i < size; i++) {
1466                count += mDeathHandlers.get(i).mMuteCount;
1467            }
1468            return count;
1469        }
1470
1471        private VolumeDeathHandler getDeathHandler(IBinder cb, boolean state) {
1472            synchronized(mDeathHandlers) {
1473                VolumeDeathHandler handler;
1474                int size = mDeathHandlers.size();
1475                for (int i = 0; i < size; i++) {
1476                    handler = mDeathHandlers.get(i);
1477                    if (cb == handler.mICallback) {
1478                        return handler;
1479                    }
1480                }
1481                // If this is the first mute request for this client, create a new
1482                // client death handler. Otherwise, it is an out of sequence unmute request.
1483                if (state) {
1484                    handler = new VolumeDeathHandler(cb);
1485                } else {
1486                    Log.w(TAG, "stream was not muted by this client");
1487                    handler = null;
1488                }
1489                return handler;
1490            }
1491        }
1492    }
1493
1494    /** Thread that handles native AudioSystem control. */
1495    private class AudioSystemThread extends Thread {
1496        AudioSystemThread() {
1497            super("AudioService");
1498        }
1499
1500        @Override
1501        public void run() {
1502            // Set this thread up so the handler will work on it
1503            Looper.prepare();
1504
1505            synchronized(AudioService.this) {
1506                mAudioHandler = new AudioHandler();
1507
1508                // Notify that the handler has been created
1509                AudioService.this.notify();
1510            }
1511
1512            // Listen for volume change requests that are set by VolumePanel
1513            Looper.loop();
1514        }
1515    }
1516
1517    /** Handles internal volume messages in separate volume thread. */
1518    private class AudioHandler extends Handler {
1519
1520        private void setSystemVolume(VolumeStreamState streamState) {
1521
1522            // Adjust volume
1523            setStreamVolumeIndex(streamState.mStreamType, streamState.mIndex);
1524
1525            // Apply change to all streams using this one as alias
1526            int numStreamTypes = AudioSystem.getNumStreamTypes();
1527            for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
1528                if (streamType != streamState.mStreamType &&
1529                    STREAM_VOLUME_ALIAS[streamType] == streamState.mStreamType) {
1530                    setStreamVolumeIndex(streamType, mStreamStates[streamType].mIndex);
1531                }
1532            }
1533
1534            // Post a persist volume msg
1535            sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamState.mStreamType,
1536                    SENDMSG_REPLACE, 1, 1, streamState, PERSIST_DELAY);
1537        }
1538
1539        private void persistVolume(VolumeStreamState streamState, boolean current, boolean lastAudible) {
1540            if (current) {
1541                System.putInt(mContentResolver, streamState.mVolumeIndexSettingName,
1542                              (streamState.mIndex + 5)/ 10);
1543            }
1544            if (lastAudible) {
1545                System.putInt(mContentResolver, streamState.mLastAudibleVolumeIndexSettingName,
1546                    (streamState.mLastAudibleIndex + 5) / 10);
1547            }
1548        }
1549
1550        private void persistRingerMode() {
1551            System.putInt(mContentResolver, System.MODE_RINGER, mRingerMode);
1552        }
1553
1554        private void persistVibrateSetting() {
1555            System.putInt(mContentResolver, System.VIBRATE_ON, mVibrateSetting);
1556        }
1557
1558        private void playSoundEffect(int effectType, int volume) {
1559            synchronized (mSoundEffectsLock) {
1560                if (mSoundPool == null) {
1561                    return;
1562                }
1563                float volFloat;
1564                // use STREAM_MUSIC volume attenuated by 3 dB if volume is not specified by caller
1565                if (volume < 0) {
1566                    // Same linear to log conversion as in native AudioSystem::linearToLog() (AudioSystem.cpp)
1567                    float dBPerStep = (float)((0.5 * 100) / MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]);
1568                    int musicVolIndex = (mStreamStates[AudioSystem.STREAM_MUSIC].mIndex + 5) / 10;
1569                    float musicVoldB = dBPerStep * (musicVolIndex - MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]);
1570                    volFloat = (float)Math.pow(10, (musicVoldB - 3)/20);
1571                } else {
1572                    volFloat = (float) volume / 1000.0f;
1573                }
1574
1575                if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) {
1576                    mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1], volFloat, volFloat, 0, 0, 1.0f);
1577                } else {
1578                    MediaPlayer mediaPlayer = new MediaPlayer();
1579                    if (mediaPlayer != null) {
1580                        try {
1581                            String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effectType][0]];
1582                            mediaPlayer.setDataSource(filePath);
1583                            mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM);
1584                            mediaPlayer.prepare();
1585                            mediaPlayer.setVolume(volFloat, volFloat);
1586                            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
1587                                public void onCompletion(MediaPlayer mp) {
1588                                    cleanupPlayer(mp);
1589                                }
1590                            });
1591                            mediaPlayer.setOnErrorListener(new OnErrorListener() {
1592                                public boolean onError(MediaPlayer mp, int what, int extra) {
1593                                    cleanupPlayer(mp);
1594                                    return true;
1595                                }
1596                            });
1597                            mediaPlayer.start();
1598                        } catch (IOException ex) {
1599                            Log.w(TAG, "MediaPlayer IOException: "+ex);
1600                        } catch (IllegalArgumentException ex) {
1601                            Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex);
1602                        } catch (IllegalStateException ex) {
1603                            Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
1604                        }
1605                    }
1606                }
1607            }
1608        }
1609
1610        private void cleanupPlayer(MediaPlayer mp) {
1611            if (mp != null) {
1612                try {
1613                    mp.stop();
1614                    mp.release();
1615                } catch (IllegalStateException ex) {
1616                    Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
1617                }
1618            }
1619        }
1620
1621        @Override
1622        public void handleMessage(Message msg) {
1623            int baseMsgWhat = getMsgBase(msg.what);
1624
1625            switch (baseMsgWhat) {
1626
1627                case MSG_SET_SYSTEM_VOLUME:
1628                    setSystemVolume((VolumeStreamState) msg.obj);
1629                    break;
1630
1631                case MSG_PERSIST_VOLUME:
1632                    persistVolume((VolumeStreamState) msg.obj, (msg.arg1 != 0), (msg.arg2 != 0));
1633                    break;
1634
1635                case MSG_PERSIST_RINGER_MODE:
1636                    persistRingerMode();
1637                    break;
1638
1639                case MSG_PERSIST_VIBRATE_SETTING:
1640                    persistVibrateSetting();
1641                    break;
1642
1643                case MSG_MEDIA_SERVER_DIED:
1644                    // Force creation of new IAudioflinger interface
1645                    if (!mMediaServerOk) {
1646                        Log.e(TAG, "Media server died.");
1647                        AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC);
1648                        sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
1649                                null, 500);
1650                    }
1651                    break;
1652
1653                case MSG_MEDIA_SERVER_STARTED:
1654                    Log.e(TAG, "Media server started.");
1655                    // indicate to audio HAL that we start the reconfiguration phase after a media
1656                    // server crash
1657                    // Note that MSG_MEDIA_SERVER_STARTED message is only received when the media server
1658                    // process restarts after a crash, not the first time it is started.
1659                    AudioSystem.setParameters("restarting=true");
1660
1661                    // Restore device connection states
1662                    Set set = mConnectedDevices.entrySet();
1663                    Iterator i = set.iterator();
1664                    while(i.hasNext()){
1665                        Map.Entry device = (Map.Entry)i.next();
1666                        AudioSystem.setDeviceConnectionState(((Integer)device.getKey()).intValue(),
1667                                                             AudioSystem.DEVICE_STATE_AVAILABLE,
1668                                                             (String)device.getValue());
1669                    }
1670
1671                    // Restore call state
1672                    AudioSystem.setPhoneState(mMode);
1673
1674                    // Restore forced usage for communcations and record
1675                    AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, mForcedUseForComm);
1676                    AudioSystem.setForceUse(AudioSystem.FOR_RECORD, mForcedUseForComm);
1677
1678                    // Restore stream volumes
1679                    int numStreamTypes = AudioSystem.getNumStreamTypes();
1680                    for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
1681                        int index;
1682                        VolumeStreamState streamState = mStreamStates[streamType];
1683                        AudioSystem.initStreamVolume(streamType, 0, (streamState.mIndexMax + 5) / 10);
1684                        if (streamState.muteCount() == 0) {
1685                            index = streamState.mIndex;
1686                        } else {
1687                            index = 0;
1688                        }
1689                        setStreamVolumeIndex(streamType, index);
1690                    }
1691
1692                    // Restore ringer mode
1693                    setRingerModeInt(getRingerMode(), false);
1694
1695                    // indicate the end of reconfiguration phase to audio HAL
1696                    AudioSystem.setParameters("restarting=false");
1697                    break;
1698
1699                case MSG_PLAY_SOUND_EFFECT:
1700                    playSoundEffect(msg.arg1, msg.arg2);
1701                    break;
1702
1703                case MSG_BTA2DP_DOCK_TIMEOUT:
1704                    // msg.obj  == address of BTA2DP device
1705                    makeA2dpDeviceUnavailableNow( (String) msg.obj );
1706                    break;
1707            }
1708        }
1709    }
1710
1711    private class SettingsObserver extends ContentObserver {
1712
1713        SettingsObserver() {
1714            super(new Handler());
1715            mContentResolver.registerContentObserver(Settings.System.getUriFor(
1716                Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this);
1717            mContentResolver.registerContentObserver(Settings.System.getUriFor(
1718                    Settings.System.NOTIFICATIONS_USE_RING_VOLUME), false, this);
1719        }
1720
1721        @Override
1722        public void onChange(boolean selfChange) {
1723            super.onChange(selfChange);
1724            synchronized (mSettingsLock) {
1725                int ringerModeAffectedStreams = Settings.System.getInt(mContentResolver,
1726                        Settings.System.MODE_RINGER_STREAMS_AFFECTED,
1727                        0);
1728                if (ringerModeAffectedStreams != mRingerModeAffectedStreams) {
1729                    /*
1730                     * Ensure all stream types that should be affected by ringer mode
1731                     * are in the proper state.
1732                     */
1733                    mRingerModeAffectedStreams = ringerModeAffectedStreams;
1734                    setRingerModeInt(getRingerMode(), false);
1735                }
1736
1737                int notificationsUseRingVolume = Settings.System.getInt(mContentResolver,
1738                        Settings.System.NOTIFICATIONS_USE_RING_VOLUME,
1739                        1);
1740                if (notificationsUseRingVolume != mNotificationsUseRingVolume) {
1741                    mNotificationsUseRingVolume = notificationsUseRingVolume;
1742                    if (mNotificationsUseRingVolume == 1) {
1743                        STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING;
1744                        mStreamStates[AudioSystem.STREAM_NOTIFICATION].setVolumeIndexSettingName(
1745                                System.VOLUME_SETTINGS[AudioSystem.STREAM_RING]);
1746                    } else {
1747                        STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_NOTIFICATION;
1748                        mStreamStates[AudioSystem.STREAM_NOTIFICATION].setVolumeIndexSettingName(
1749                                System.VOLUME_SETTINGS[AudioSystem.STREAM_NOTIFICATION]);
1750                        // Persist notification volume volume as it was not persisted while aliased to ring volume
1751                        //  and persist with no delay as there might be registered observers of the persisted
1752                        //  notification volume.
1753                        sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, AudioSystem.STREAM_NOTIFICATION,
1754                                SENDMSG_REPLACE, 1, 1, mStreamStates[AudioSystem.STREAM_NOTIFICATION], 0);
1755                    }
1756                }
1757            }
1758        }
1759    }
1760
1761    private void makeA2dpDeviceAvailable(String address) {
1762        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
1763                AudioSystem.DEVICE_STATE_AVAILABLE,
1764                address);
1765        // Reset A2DP suspend state each time a new sink is connected
1766        AudioSystem.setParameters("A2dpSuspended=false");
1767        mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP),
1768                address);
1769    }
1770
1771    private void makeA2dpDeviceUnavailableNow(String address) {
1772        Intent noisyIntent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
1773        mContext.sendBroadcast(noisyIntent);
1774        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
1775                AudioSystem.DEVICE_STATE_UNAVAILABLE,
1776                address);
1777        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
1778    }
1779
1780    private void makeA2dpDeviceUnavailableLater(String address) {
1781        // prevent any activity on the A2DP audio output to avoid unwanted
1782        // reconnection of the sink.
1783        AudioSystem.setParameters("A2dpSuspended=true");
1784        // the device will be made unavailable later, so consider it disconnected right away
1785        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
1786        // send the delayed message to make the device unavailable later
1787        Message msg = mAudioHandler.obtainMessage(MSG_BTA2DP_DOCK_TIMEOUT, address);
1788        mAudioHandler.sendMessageDelayed(msg, BTA2DP_DOCK_TIMEOUT_MILLIS);
1789
1790    }
1791
1792    private void cancelA2dpDeviceTimeout() {
1793        mAudioHandler.removeMessages(MSG_BTA2DP_DOCK_TIMEOUT);
1794    }
1795
1796    private boolean hasScheduledA2dpDockTimeout() {
1797        return mAudioHandler.hasMessages(MSG_BTA2DP_DOCK_TIMEOUT);
1798    }
1799
1800    /* cache of the address of the last dock the device was connected to */
1801    private String mDockAddress;
1802
1803    /**
1804     * Receiver for misc intent broadcasts the Phone app cares about.
1805     */
1806    private class AudioServiceBroadcastReceiver extends BroadcastReceiver {
1807        @Override
1808        public void onReceive(Context context, Intent intent) {
1809            String action = intent.getAction();
1810
1811            if (action.equals(Intent.ACTION_DOCK_EVENT)) {
1812                int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
1813                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
1814                int config;
1815                switch (dockState) {
1816                    case Intent.EXTRA_DOCK_STATE_DESK:
1817                        config = AudioSystem.FORCE_BT_DESK_DOCK;
1818                        break;
1819                    case Intent.EXTRA_DOCK_STATE_CAR:
1820                        config = AudioSystem.FORCE_BT_CAR_DOCK;
1821                        break;
1822                    case Intent.EXTRA_DOCK_STATE_LE_DESK:
1823                        config = AudioSystem.FORCE_ANALOG_DOCK;
1824                        break;
1825                    case Intent.EXTRA_DOCK_STATE_HE_DESK:
1826                        config = AudioSystem.FORCE_DIGITAL_DOCK;
1827                        break;
1828                    case Intent.EXTRA_DOCK_STATE_UNDOCKED:
1829                    default:
1830                        config = AudioSystem.FORCE_NONE;
1831                }
1832                AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
1833            } else if (action.equals(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED)) {
1834                int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
1835                                               BluetoothProfile.STATE_DISCONNECTED);
1836                BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
1837                String address = btDevice.getAddress();
1838                boolean isConnected =
1839                    (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP) &&
1840                     mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP).equals(address));
1841
1842                if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
1843                    if (btDevice.isBluetoothDock()) {
1844                        if (state == BluetoothProfile.STATE_DISCONNECTED) {
1845                            // introduction of a delay for transient disconnections of docks when
1846                            // power is rapidly turned off/on, this message will be canceled if
1847                            // we reconnect the dock under a preset delay
1848                            makeA2dpDeviceUnavailableLater(address);
1849                            // the next time isConnected is evaluated, it will be false for the dock
1850                        }
1851                    } else {
1852                        makeA2dpDeviceUnavailableNow(address);
1853                    }
1854                } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
1855                    if (btDevice.isBluetoothDock()) {
1856                        // this could be a reconnection after a transient disconnection
1857                        cancelA2dpDeviceTimeout();
1858                        mDockAddress = address;
1859                    } else {
1860                        // this could be a connection of another A2DP device before the timeout of
1861                        // a dock: cancel the dock timeout, and make the dock unavailable now
1862                        if(hasScheduledA2dpDockTimeout()) {
1863                            cancelA2dpDeviceTimeout();
1864                            makeA2dpDeviceUnavailableNow(mDockAddress);
1865                        }
1866                    }
1867                    makeA2dpDeviceAvailable(address);
1868                }
1869            } else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
1870                int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
1871                                               BluetoothProfile.STATE_DISCONNECTED);
1872                int device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
1873                BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
1874                String address = null;
1875                if (btDevice != null) {
1876                    address = btDevice.getAddress();
1877                    BluetoothClass btClass = btDevice.getBluetoothClass();
1878                    if (btClass != null) {
1879                        switch (btClass.getDeviceClass()) {
1880                        case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET:
1881                        case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
1882                            device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
1883                            break;
1884                        case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO:
1885                            device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1886                            break;
1887                        }
1888                    }
1889                }
1890
1891                boolean isConnected = (mConnectedDevices.containsKey(device) &&
1892                                       mConnectedDevices.get(device).equals(address));
1893
1894                if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
1895                    AudioSystem.setDeviceConnectionState(device,
1896                                                         AudioSystem.DEVICE_STATE_UNAVAILABLE,
1897                                                         address);
1898                    mConnectedDevices.remove(device);
1899                    mBluetoothHeadsetDevice = null;
1900                    clearAllScoClients();
1901                } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
1902                    AudioSystem.setDeviceConnectionState(device,
1903                                                         AudioSystem.DEVICE_STATE_AVAILABLE,
1904                                                         address);
1905                    mConnectedDevices.put(new Integer(device), address);
1906                    mBluetoothHeadsetDevice = btDevice;
1907                }
1908            } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
1909                int state = intent.getIntExtra("state", 0);
1910                int microphone = intent.getIntExtra("microphone", 0);
1911
1912                if (microphone != 0) {
1913                    boolean isConnected = mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADSET);
1914                    if (state == 0 && isConnected) {
1915                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,
1916                                AudioSystem.DEVICE_STATE_UNAVAILABLE,
1917                                "");
1918                        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADSET);
1919                    } else if (state == 1 && !isConnected)  {
1920                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,
1921                                AudioSystem.DEVICE_STATE_AVAILABLE,
1922                                "");
1923                        mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADSET), "");
1924                    }
1925                } else {
1926                    boolean isConnected = mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE);
1927                    if (state == 0 && isConnected) {
1928                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE,
1929                                AudioSystem.DEVICE_STATE_UNAVAILABLE,
1930                                "");
1931                        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE);
1932                    } else if (state == 1 && !isConnected)  {
1933                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE,
1934                                AudioSystem.DEVICE_STATE_AVAILABLE,
1935                                "");
1936                        mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE), "");
1937                    }
1938                }
1939            } else if (action.equals(Intent.ACTION_USB_ANLG_HEADSET_PLUG)) {
1940                int state = intent.getIntExtra("state", 0);
1941                Log.v(TAG, "Broadcast Receiver: Got ACTION_USB_ANLG_HEADSET_PLUG, state = "+state);
1942                boolean isConnected = mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET);
1943                if (state == 0 && isConnected) {
1944                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET,
1945                                                         AudioSystem.DEVICE_STATE_UNAVAILABLE, "");
1946                    mConnectedDevices.remove(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET);
1947                } else if (state == 1 && !isConnected)  {
1948                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET,
1949                                                         AudioSystem.DEVICE_STATE_AVAILABLE, "");
1950                    mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET), "");
1951                }
1952            } else if (action.equals(Intent.ACTION_USB_DGTL_HEADSET_PLUG)) {
1953                int state = intent.getIntExtra("state", 0);
1954                Log.v(TAG, "Broadcast Receiver: Got ACTION_USB_DGTL_HEADSET_PLUG, state = "+state);
1955                boolean isConnected = mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET);
1956                if (state == 0 && isConnected) {
1957                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET,
1958                                                         AudioSystem.DEVICE_STATE_UNAVAILABLE, "");
1959                    mConnectedDevices.remove(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET);
1960                } else if (state == 1 && !isConnected)  {
1961                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET,
1962                                                         AudioSystem.DEVICE_STATE_AVAILABLE, "");
1963                    mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET), "");
1964                }
1965            } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) {
1966                int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1);
1967                synchronized (mScoClients) {
1968                    if (!mScoClients.isEmpty()) {
1969                        switch (state) {
1970                        case BluetoothHeadset.STATE_AUDIO_CONNECTED:
1971                            state = AudioManager.SCO_AUDIO_STATE_CONNECTED;
1972                            break;
1973                        case BluetoothHeadset.STATE_AUDIO_DISCONNECTED:
1974                            state = AudioManager.SCO_AUDIO_STATE_DISCONNECTED;
1975                            break;
1976                        case BluetoothHeadset.STATE_AUDIO_CONNECTING:
1977                            // Todo(): Handle this, ignore for now as a public
1978                            // API will break.
1979                            break;
1980                        default:
1981                            state = AudioManager.SCO_AUDIO_STATE_ERROR;
1982                            break;
1983                        }
1984                        if (state != AudioManager.SCO_AUDIO_STATE_ERROR) {
1985                            Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
1986                            newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, state);
1987                            mContext.sendStickyBroadcast(newIntent);
1988                        }
1989                    }
1990                }
1991            }
1992        }
1993    }
1994
1995    //==========================================================================================
1996    // AudioFocus
1997    //==========================================================================================
1998
1999    /* constant to identify focus stack entry that is used to hold the focus while the phone
2000     * is ringing or during a call
2001     */
2002    private final static String IN_VOICE_COMM_FOCUS_ID = "AudioFocus_For_Phone_Ring_And_Calls";
2003
2004    private final static Object mAudioFocusLock = new Object();
2005
2006    private final static Object mRingingLock = new Object();
2007
2008    private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
2009        @Override
2010        public void onCallStateChanged(int state, String incomingNumber) {
2011            if (state == TelephonyManager.CALL_STATE_RINGING) {
2012                //Log.v(TAG, " CALL_STATE_RINGING");
2013                synchronized(mRingingLock) {
2014                    mIsRinging = true;
2015                }
2016                int ringVolume = AudioService.this.getStreamVolume(AudioManager.STREAM_RING);
2017                if (ringVolume > 0) {
2018                    requestAudioFocus(AudioManager.STREAM_RING,
2019                                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT,
2020                                null, null /* both allowed to be null only for this clientId */,
2021                                IN_VOICE_COMM_FOCUS_ID /*clientId*/);
2022                }
2023            } else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
2024                //Log.v(TAG, " CALL_STATE_OFFHOOK");
2025                synchronized(mRingingLock) {
2026                    mIsRinging = false;
2027                }
2028                requestAudioFocus(AudioManager.STREAM_RING,
2029                        AudioManager.AUDIOFOCUS_GAIN_TRANSIENT,
2030                        null, null /* both allowed to be null only for this clientId */,
2031                        IN_VOICE_COMM_FOCUS_ID /*clientId*/);
2032            } else if (state == TelephonyManager.CALL_STATE_IDLE) {
2033                //Log.v(TAG, " CALL_STATE_IDLE");
2034                synchronized(mRingingLock) {
2035                    mIsRinging = false;
2036                }
2037                abandonAudioFocus(null, IN_VOICE_COMM_FOCUS_ID);
2038            }
2039        }
2040    };
2041
2042    private void notifyTopOfAudioFocusStack() {
2043        // notify the top of the stack it gained focus
2044        if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) {
2045            if (canReassignAudioFocus()) {
2046                try {
2047                    mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange(
2048                            AudioManager.AUDIOFOCUS_GAIN, mFocusStack.peek().mClientId);
2049                } catch (RemoteException e) {
2050                    Log.e(TAG, "Failure to signal gain of audio control focus due to "+ e);
2051                    e.printStackTrace();
2052                }
2053            }
2054        }
2055    }
2056
2057    private static class FocusStackEntry {
2058        public int mStreamType = -1;// no stream type
2059        public boolean mIsTransportControlReceiver = false;
2060        public IAudioFocusDispatcher mFocusDispatcher = null;
2061        public IBinder mSourceRef = null;
2062        public String mClientId;
2063        public int mFocusChangeType;
2064
2065        public FocusStackEntry() {
2066        }
2067
2068        public FocusStackEntry(int streamType, int duration, boolean isTransportControlReceiver,
2069                IAudioFocusDispatcher afl, IBinder source, String id) {
2070            mStreamType = streamType;
2071            mIsTransportControlReceiver = isTransportControlReceiver;
2072            mFocusDispatcher = afl;
2073            mSourceRef = source;
2074            mClientId = id;
2075            mFocusChangeType = duration;
2076        }
2077    }
2078
2079    private Stack<FocusStackEntry> mFocusStack = new Stack<FocusStackEntry>();
2080
2081    /**
2082     * Helper function:
2083     * Display in the log the current entries in the audio focus stack
2084     */
2085    private void dumpFocusStack(PrintWriter pw) {
2086        pw.println("\nAudio Focus stack entries:");
2087        synchronized(mAudioFocusLock) {
2088            Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
2089            while(stackIterator.hasNext()) {
2090                FocusStackEntry fse = stackIterator.next();
2091                pw.println("     source:" + fse.mSourceRef + " -- client: " + fse.mClientId
2092                        + " -- duration: " +fse.mFocusChangeType);
2093            }
2094        }
2095    }
2096
2097    /**
2098     * Helper function:
2099     * Remove a focus listener from the focus stack.
2100     * @param focusListenerToRemove the focus listener
2101     * @param signal if true and the listener was at the top of the focus stack, i.e. it was holding
2102     *   focus, notify the next item in the stack it gained focus.
2103     */
2104    private void removeFocusStackEntry(String clientToRemove, boolean signal) {
2105        // is the current top of the focus stack abandoning focus? (because of death or request)
2106        if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientToRemove))
2107        {
2108            //Log.i(TAG, "   removeFocusStackEntry() removing top of stack");
2109            mFocusStack.pop();
2110            if (signal) {
2111                // notify the new top of the stack it gained focus
2112                notifyTopOfAudioFocusStack();
2113            }
2114        } else {
2115            // focus is abandoned by a client that's not at the top of the stack,
2116            // no need to update focus.
2117            Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
2118            while(stackIterator.hasNext()) {
2119                FocusStackEntry fse = (FocusStackEntry)stackIterator.next();
2120                if(fse.mClientId.equals(clientToRemove)) {
2121                    Log.i(TAG, " AudioFocus  abandonAudioFocus(): removing entry for "
2122                            + fse.mClientId);
2123                    mFocusStack.remove(fse);
2124                }
2125            }
2126        }
2127    }
2128
2129    /**
2130     * Helper function:
2131     * Remove focus listeners from the focus stack for a particular client.
2132     */
2133    private void removeFocusStackEntryForClient(IBinder cb) {
2134        // is the owner of the audio focus part of the client to remove?
2135        boolean isTopOfStackForClientToRemove = !mFocusStack.isEmpty() &&
2136                mFocusStack.peek().mSourceRef.equals(cb);
2137        Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
2138        while(stackIterator.hasNext()) {
2139            FocusStackEntry fse = (FocusStackEntry)stackIterator.next();
2140            if(fse.mSourceRef.equals(cb)) {
2141                Log.i(TAG, " AudioFocus  abandonAudioFocus(): removing entry for "
2142                        + fse.mClientId);
2143                mFocusStack.remove(fse);
2144            }
2145        }
2146        if (isTopOfStackForClientToRemove) {
2147            // we removed an entry at the top of the stack:
2148            //  notify the new top of the stack it gained focus.
2149            notifyTopOfAudioFocusStack();
2150        }
2151    }
2152
2153    /**
2154     * Helper function:
2155     * Returns true if the system is in a state where the focus can be reevaluated, false otherwise.
2156     */
2157    private boolean canReassignAudioFocus() {
2158        // focus requests are rejected during a phone call or when the phone is ringing
2159        // this is equivalent to IN_VOICE_COMM_FOCUS_ID having the focus
2160        if (!mFocusStack.isEmpty() && IN_VOICE_COMM_FOCUS_ID.equals(mFocusStack.peek().mClientId)) {
2161            return false;
2162        }
2163        return true;
2164    }
2165
2166    /**
2167     * Inner class to monitor audio focus client deaths, and remove them from the audio focus
2168     * stack if necessary.
2169     */
2170    private class AudioFocusDeathHandler implements IBinder.DeathRecipient {
2171        private IBinder mCb; // To be notified of client's death
2172
2173        AudioFocusDeathHandler(IBinder cb) {
2174            mCb = cb;
2175        }
2176
2177        public void binderDied() {
2178            synchronized(mAudioFocusLock) {
2179                Log.w(TAG, "  AudioFocus   audio focus client died");
2180                removeFocusStackEntryForClient(mCb);
2181            }
2182        }
2183
2184        public IBinder getBinder() {
2185            return mCb;
2186        }
2187    }
2188
2189
2190    /** @see AudioManager#requestAudioFocus(IAudioFocusDispatcher, int, int) */
2191    public int requestAudioFocus(int mainStreamType, int focusChangeHint, IBinder cb,
2192            IAudioFocusDispatcher fd, String clientId) {
2193        Log.i(TAG, " AudioFocus  requestAudioFocus() from " + clientId);
2194        // the main stream type for the audio focus request is currently not used. It may
2195        // potentially be used to handle multiple stream type-dependent audio focuses.
2196
2197        // we need a valid binder callback for clients other than the AudioService's phone
2198        // state listener
2199        if (!IN_VOICE_COMM_FOCUS_ID.equals(clientId) && ((cb == null) || !cb.pingBinder())) {
2200            Log.i(TAG, " AudioFocus  DOA client for requestAudioFocus(), exiting");
2201            return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
2202        }
2203
2204        synchronized(mAudioFocusLock) {
2205            if (!canReassignAudioFocus()) {
2206                return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
2207            }
2208
2209            if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientId)) {
2210                // if focus is already owned by this client and the reason for acquiring the focus
2211                // hasn't changed, don't do anything
2212                if (mFocusStack.peek().mFocusChangeType == focusChangeHint) {
2213                    return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
2214                }
2215                // the reason for the audio focus request has changed: remove the current top of
2216                // stack and respond as if we had a new focus owner
2217                mFocusStack.pop();
2218            }
2219
2220            // notify current top of stack it is losing focus
2221            if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) {
2222                try {
2223                    mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange(
2224                            -1 * focusChangeHint, // loss and gain codes are inverse of each other
2225                            mFocusStack.peek().mClientId);
2226                } catch (RemoteException e) {
2227                    Log.e(TAG, " Failure to signal loss of focus due to "+ e);
2228                    e.printStackTrace();
2229                }
2230            }
2231
2232            // focus requester might already be somewhere below in the stack, remove it
2233            removeFocusStackEntry(clientId, false);
2234
2235            // push focus requester at the top of the audio focus stack
2236            mFocusStack.push(new FocusStackEntry(mainStreamType, focusChangeHint, false, fd, cb,
2237                    clientId));
2238        }//synchronized(mAudioFocusLock)
2239
2240        // handle the potential premature death of the new holder of the focus
2241        // (premature death == death before abandoning focus) for a client which is not the
2242        // AudioService's phone state listener
2243        if (!IN_VOICE_COMM_FOCUS_ID.equals(clientId)) {
2244            // Register for client death notification
2245            AudioFocusDeathHandler afdh = new AudioFocusDeathHandler(cb);
2246            try {
2247                cb.linkToDeath(afdh, 0);
2248            } catch (RemoteException e) {
2249                // client has already died!
2250                Log.w(TAG, "AudioFocus  requestAudioFocus() could not link to "+cb+" binder death");
2251            }
2252        }
2253
2254        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
2255    }
2256
2257    /** @see AudioManager#abandonAudioFocus(IAudioFocusDispatcher) */
2258    public int abandonAudioFocus(IAudioFocusDispatcher fl, String clientId) {
2259        Log.i(TAG, " AudioFocus  abandonAudioFocus() from " + clientId);
2260        try {
2261            // this will take care of notifying the new focus owner if needed
2262            synchronized(mAudioFocusLock) {
2263                removeFocusStackEntry(clientId, true);
2264            }
2265        } catch (java.util.ConcurrentModificationException cme) {
2266            // Catching this exception here is temporary. It is here just to prevent
2267            // a crash seen when the "Silent" notification is played. This is believed to be fixed
2268            // but this try catch block is left just to be safe.
2269            Log.e(TAG, "FATAL EXCEPTION AudioFocus  abandonAudioFocus() caused " + cme);
2270            cme.printStackTrace();
2271        }
2272
2273        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
2274    }
2275
2276
2277    public void unregisterAudioFocusClient(String clientId) {
2278        synchronized(mAudioFocusLock) {
2279            removeFocusStackEntry(clientId, false);
2280        }
2281    }
2282
2283
2284    //==========================================================================================
2285    // RemoteControl
2286    //==========================================================================================
2287    /**
2288     * Receiver for media button intents. Handles the dispatching of the media button event
2289     * to one of the registered listeners, or if there was none, resumes the intent broadcast
2290     * to the rest of the system.
2291     */
2292    private class MediaButtonBroadcastReceiver extends BroadcastReceiver {
2293        @Override
2294        public void onReceive(Context context, Intent intent) {
2295            String action = intent.getAction();
2296            if (!Intent.ACTION_MEDIA_BUTTON.equals(action)) {
2297                return;
2298            }
2299            KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
2300            if (event != null) {
2301                // if in a call or ringing, do not break the current phone app behavior
2302                // TODO modify this to let the phone app specifically get the RC focus
2303                //      add modify the phone app to take advantage of the new API
2304                synchronized(mRingingLock) {
2305                    if (mIsRinging || (getMode() == AudioSystem.MODE_IN_CALL) ||
2306                            (getMode() == AudioSystem.MODE_RINGTONE) ) {
2307                        return;
2308                    }
2309                }
2310                synchronized(mRCStack) {
2311                    if (!mRCStack.empty()) {
2312                        // create a new intent specifically aimed at the current registered listener
2313                        Intent targetedIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
2314                        targetedIntent.putExtras(intent.getExtras());
2315                        targetedIntent.setComponent(mRCStack.peek().mReceiverComponent);
2316                        // trap the current broadcast
2317                        abortBroadcast();
2318                        //Log.v(TAG, " Sending intent" + targetedIntent);
2319                        context.sendBroadcast(targetedIntent, null);
2320                    }
2321                }
2322            }
2323        }
2324    }
2325
2326    private static class RemoteControlStackEntry {
2327        public ComponentName mReceiverComponent;// always non null
2328        // TODO implement registration expiration?
2329        //public int mRegistrationTime;
2330
2331        public RemoteControlStackEntry() {
2332        }
2333
2334        public RemoteControlStackEntry(ComponentName r) {
2335            mReceiverComponent = r;
2336        }
2337    }
2338
2339    private Stack<RemoteControlStackEntry> mRCStack = new Stack<RemoteControlStackEntry>();
2340
2341    /**
2342     * Helper function:
2343     * Display in the log the current entries in the remote control focus stack
2344     */
2345    private void dumpRCStack(PrintWriter pw) {
2346        pw.println("\nRemote Control stack entries:");
2347        synchronized(mRCStack) {
2348            Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
2349            while(stackIterator.hasNext()) {
2350                RemoteControlStackEntry fse = stackIterator.next();
2351                pw.println("     receiver:" + fse.mReceiverComponent);
2352            }
2353        }
2354    }
2355
2356    /**
2357     * Helper function:
2358     * Set the new remote control receiver at the top of the RC focus stack
2359     */
2360    private void pushMediaButtonReceiver(ComponentName newReceiver) {
2361        // already at top of stack?
2362        if (!mRCStack.empty() && mRCStack.peek().mReceiverComponent.equals(newReceiver)) {
2363            return;
2364        }
2365        Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
2366        while(stackIterator.hasNext()) {
2367            RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
2368            if(rcse.mReceiverComponent.equals(newReceiver)) {
2369                mRCStack.remove(rcse);
2370                break;
2371            }
2372        }
2373        mRCStack.push(new RemoteControlStackEntry(newReceiver));
2374    }
2375
2376    /**
2377     * Helper function:
2378     * Remove the remote control receiver from the RC focus stack
2379     */
2380    private void removeMediaButtonReceiver(ComponentName newReceiver) {
2381        Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
2382        while(stackIterator.hasNext()) {
2383            RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
2384            if(rcse.mReceiverComponent.equals(newReceiver)) {
2385                mRCStack.remove(rcse);
2386                break;
2387            }
2388        }
2389    }
2390
2391
2392    /** see AudioManager.registerMediaButtonEventReceiver(ComponentName eventReceiver) */
2393    public void registerMediaButtonEventReceiver(ComponentName eventReceiver) {
2394        Log.i(TAG, "  Remote Control   registerMediaButtonEventReceiver() for " + eventReceiver);
2395
2396        synchronized(mRCStack) {
2397            pushMediaButtonReceiver(eventReceiver);
2398        }
2399    }
2400
2401    /** see AudioManager.unregisterMediaButtonEventReceiver(ComponentName eventReceiver) */
2402    public void unregisterMediaButtonEventReceiver(ComponentName eventReceiver) {
2403        Log.i(TAG, "  Remote Control   unregisterMediaButtonEventReceiver() for " + eventReceiver);
2404
2405        synchronized(mRCStack) {
2406            removeMediaButtonReceiver(eventReceiver);
2407        }
2408    }
2409
2410
2411    @Override
2412    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2413        // TODO probably a lot more to do here than just the audio focus and remote control stacks
2414        dumpFocusStack(pw);
2415        dumpRCStack(pw);
2416    }
2417
2418
2419}
2420