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