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