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