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