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