AudioService.java revision d327f21626217aa3c9c0cdb7a84a742c531e59a3
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.content.BroadcastReceiver;
21import android.content.ComponentName;
22import android.content.ContentResolver;
23import android.content.Context;
24import android.content.Intent;
25import android.content.IntentFilter;
26import android.bluetooth.BluetoothA2dp;
27import android.bluetooth.BluetoothClass;
28import android.bluetooth.BluetoothDevice;
29import android.bluetooth.BluetoothHeadset;
30import android.content.pm.PackageManager;
31import android.database.ContentObserver;
32import android.media.MediaPlayer.OnCompletionListener;
33import android.media.MediaPlayer.OnErrorListener;
34import android.os.Binder;
35import android.os.Environment;
36import android.os.Handler;
37import android.os.IBinder;
38import android.os.Looper;
39import android.os.Message;
40import android.os.RemoteException;
41import android.os.ServiceManager;
42import android.provider.Settings;
43import android.provider.Settings.System;
44import android.util.Log;
45import android.view.KeyEvent;
46import android.view.VolumePanel;
47import android.os.SystemProperties;
48
49import com.android.internal.telephony.ITelephony;
50
51import java.io.FileDescriptor;
52import java.io.IOException;
53import java.io.PrintWriter;
54import java.util.ArrayList;
55import java.util.HashMap;
56import java.util.Iterator;
57import java.util.Map;
58import java.util.Set;
59import java.util.Stack;
60
61/**
62 * The implementation of the volume manager service.
63 * <p>
64 * This implementation focuses on delivering a responsive UI. Most methods are
65 * asynchronous to external calls. For example, the task of setting a volume
66 * will update our internal state, but in a separate thread will set the system
67 * volume and later persist to the database. Similarly, setting the ringer mode
68 * will update the state and broadcast a change and in a separate thread later
69 * persist the ringer mode.
70 *
71 * @hide
72 */
73public class AudioService extends IAudioService.Stub {
74
75    private static final String TAG = "AudioService";
76
77    /** How long to delay before persisting a change in volume/ringer mode. */
78    private static final int PERSIST_DELAY = 3000;
79
80    private Context mContext;
81    private ContentResolver mContentResolver;
82
83
84    /** The UI */
85    private VolumePanel mVolumePanel;
86
87    // sendMsg() flags
88    /** Used when a message should be shared across all stream types. */
89    private static final int SHARED_MSG = -1;
90    /** If the msg is already queued, replace it with this one. */
91    private static final int SENDMSG_REPLACE = 0;
92    /** If the msg is already queued, ignore this one and leave the old. */
93    private static final int SENDMSG_NOOP = 1;
94    /** If the msg is already queued, queue this one and leave the old. */
95    private static final int SENDMSG_QUEUE = 2;
96
97    // AudioHandler message.whats
98    private static final int MSG_SET_SYSTEM_VOLUME = 0;
99    private static final int MSG_PERSIST_VOLUME = 1;
100    private static final int MSG_PERSIST_RINGER_MODE = 3;
101    private static final int MSG_PERSIST_VIBRATE_SETTING = 4;
102    private static final int MSG_MEDIA_SERVER_DIED = 5;
103    private static final int MSG_MEDIA_SERVER_STARTED = 6;
104    private static final int MSG_PLAY_SOUND_EFFECT = 7;
105
106    /** @see AudioSystemThread */
107    private AudioSystemThread mAudioSystemThread;
108    /** @see AudioHandler */
109    private AudioHandler mAudioHandler;
110    /** @see VolumeStreamState */
111    private VolumeStreamState[] mStreamStates;
112    private SettingsObserver mSettingsObserver;
113
114    private int mMode;
115    private Object mSettingsLock = new Object();
116    private boolean mMediaServerOk;
117
118    private SoundPool mSoundPool;
119    private Object mSoundEffectsLock = new Object();
120    private static final int NUM_SOUNDPOOL_CHANNELS = 4;
121    private static final int SOUND_EFFECT_VOLUME = 1000;
122
123    /* Sound effect file names  */
124    private static final String SOUND_EFFECTS_PATH = "/media/audio/ui/";
125    private static final String[] SOUND_EFFECT_FILES = new String[] {
126        "Effect_Tick.ogg",
127        "KeypressStandard.ogg",
128        "KeypressSpacebar.ogg",
129        "KeypressDelete.ogg",
130        "KeypressReturn.ogg"
131    };
132
133    /* Sound effect file name mapping sound effect id (AudioManager.FX_xxx) to
134     * file index in SOUND_EFFECT_FILES[] (first column) and indicating if effect
135     * uses soundpool (second column) */
136    private int[][] SOUND_EFFECT_FILES_MAP = new int[][] {
137        {0, -1},  // FX_KEY_CLICK
138        {0, -1},  // FX_FOCUS_NAVIGATION_UP
139        {0, -1},  // FX_FOCUS_NAVIGATION_DOWN
140        {0, -1},  // FX_FOCUS_NAVIGATION_LEFT
141        {0, -1},  // FX_FOCUS_NAVIGATION_RIGHT
142        {1, -1},  // FX_KEYPRESS_STANDARD
143        {2, -1},  // FX_KEYPRESS_SPACEBAR
144        {3, -1},  // FX_FOCUS_DELETE
145        {4, -1}   // FX_FOCUS_RETURN
146    };
147
148   /** @hide Maximum volume index values for audio streams */
149    private int[] MAX_STREAM_VOLUME = new int[] {
150        5,  // STREAM_VOICE_CALL
151        7,  // STREAM_SYSTEM
152        7,  // STREAM_RING
153        15, // STREAM_MUSIC
154        7,  // STREAM_ALARM
155        7,  // STREAM_NOTIFICATION
156        15, // STREAM_BLUETOOTH_SCO
157        7,  // STREAM_SYSTEM_ENFORCED
158        15, // STREAM_DTMF
159        15  // STREAM_TTS
160    };
161    /* STREAM_VOLUME_ALIAS[] indicates for each stream if it uses the volume settings
162     * of another stream: This avoids multiplying the volume settings for hidden
163     * stream types that follow other stream behavior for volume settings
164     * NOTE: do not create loops in aliases! */
165    private int[] STREAM_VOLUME_ALIAS = new int[] {
166        AudioSystem.STREAM_VOICE_CALL,  // STREAM_VOICE_CALL
167        AudioSystem.STREAM_SYSTEM,  // STREAM_SYSTEM
168        AudioSystem.STREAM_RING,  // STREAM_RING
169        AudioSystem.STREAM_MUSIC, // STREAM_MUSIC
170        AudioSystem.STREAM_ALARM,  // STREAM_ALARM
171        AudioSystem.STREAM_NOTIFICATION,  // STREAM_NOTIFICATION
172        AudioSystem.STREAM_BLUETOOTH_SCO, // STREAM_BLUETOOTH_SCO
173        AudioSystem.STREAM_SYSTEM,  // STREAM_SYSTEM_ENFORCED
174        AudioSystem.STREAM_VOICE_CALL, // STREAM_DTMF
175        AudioSystem.STREAM_MUSIC  // STREAM_TTS
176    };
177
178    private AudioSystem.ErrorCallback mAudioSystemCallback = new AudioSystem.ErrorCallback() {
179        public void onError(int error) {
180            switch (error) {
181            case AudioSystem.AUDIO_STATUS_SERVER_DIED:
182                if (mMediaServerOk) {
183                    sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
184                            null, 1500);
185                    mMediaServerOk = false;
186                }
187                break;
188            case AudioSystem.AUDIO_STATUS_OK:
189                if (!mMediaServerOk) {
190                    sendMsg(mAudioHandler, MSG_MEDIA_SERVER_STARTED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
191                            null, 0);
192                    mMediaServerOk = true;
193                }
194                break;
195            default:
196                break;
197            }
198       }
199    };
200
201    /**
202     * Current ringer mode from one of {@link AudioManager#RINGER_MODE_NORMAL},
203     * {@link AudioManager#RINGER_MODE_SILENT}, or
204     * {@link AudioManager#RINGER_MODE_VIBRATE}.
205     */
206    private int mRingerMode;
207
208    /** @see System#MODE_RINGER_STREAMS_AFFECTED */
209    private int mRingerModeAffectedStreams;
210
211    /** @see System#MUTE_STREAMS_AFFECTED */
212    private int mMuteAffectedStreams;
213
214    /**
215     * Has multiple bits per vibrate type to indicate the type's vibrate
216     * setting. See {@link #setVibrateSetting(int, int)}.
217     * <p>
218     * NOTE: This is not the final decision of whether vibrate is on/off for the
219     * type since it depends on the ringer mode. See {@link #shouldVibrate(int)}.
220     */
221    private int mVibrateSetting;
222
223    /** @see System#NOTIFICATIONS_USE_RING_VOLUME */
224    private int mNotificationsUseRingVolume;
225
226    // Broadcast receiver for device connections intent broadcasts
227    private final BroadcastReceiver mReceiver = new AudioServiceBroadcastReceiver();
228
229    //  Broadcast receiver for media button broadcasts (separate from mReceiver to
230    //  independently change its priority)
231    private final BroadcastReceiver mMediaButtonReceiver = new MediaButtonBroadcastReceiver();
232
233    // Devices currently connected
234    private HashMap <Integer, String> mConnectedDevices = new HashMap <Integer, String>();
235
236    // Forced device usage for communications
237    private int mForcedUseForComm;
238
239    // List of binder death handlers for setMode() client processes.
240    // The last process to have called setMode() is at the top of the list.
241    private ArrayList <SetModeDeathHandler> mSetModeDeathHandlers = new ArrayList <SetModeDeathHandler>();
242
243    ///////////////////////////////////////////////////////////////////////////
244    // Construction
245    ///////////////////////////////////////////////////////////////////////////
246
247    /** @hide */
248    public AudioService(Context context) {
249        mContext = context;
250        mContentResolver = context.getContentResolver();
251
252       // Intialized volume
253        MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = SystemProperties.getInt(
254            "ro.config.vc_call_vol_steps",
255           MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]);
256
257        mVolumePanel = new VolumePanel(context, this);
258        mSettingsObserver = new SettingsObserver();
259        mForcedUseForComm = AudioSystem.FORCE_NONE;
260        createAudioSystemThread();
261        readPersistedSettings();
262        createStreamStates();
263        // Call setMode() to initialize mSetModeDeathHandlers
264        mMode = AudioSystem.MODE_INVALID;
265        setMode(AudioSystem.MODE_NORMAL, null);
266        mMediaServerOk = true;
267        AudioSystem.setErrorCallback(mAudioSystemCallback);
268        loadSoundEffects();
269
270        // Register for device connection intent broadcasts.
271        IntentFilter intentFilter =
272                new IntentFilter(Intent.ACTION_HEADSET_PLUG);
273        intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
274        intentFilter.addAction(BluetoothHeadset.ACTION_STATE_CHANGED);
275        intentFilter.addAction(Intent.ACTION_DOCK_EVENT);
276        context.registerReceiver(mReceiver, intentFilter);
277
278        // Register for media button intent broadcasts.
279        intentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
280        intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
281        context.registerReceiver(mMediaButtonReceiver, intentFilter);
282    }
283
284    private void createAudioSystemThread() {
285        mAudioSystemThread = new AudioSystemThread();
286        mAudioSystemThread.start();
287        waitForAudioHandlerCreation();
288    }
289
290    /** Waits for the volume handler to be created by the other thread. */
291    private void waitForAudioHandlerCreation() {
292        synchronized(this) {
293            while (mAudioHandler == null) {
294                try {
295                    // Wait for mAudioHandler to be set by the other thread
296                    wait();
297                } catch (InterruptedException e) {
298                    Log.e(TAG, "Interrupted while waiting on volume handler.");
299                }
300            }
301        }
302    }
303
304    private void createStreamStates() {
305        int numStreamTypes = AudioSystem.getNumStreamTypes();
306        VolumeStreamState[] streams = mStreamStates = new VolumeStreamState[numStreamTypes];
307
308        for (int i = 0; i < numStreamTypes; i++) {
309            streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[i]], i);
310        }
311
312        // Correct stream index values for streams with aliases
313        for (int i = 0; i < numStreamTypes; i++) {
314            if (STREAM_VOLUME_ALIAS[i] != i) {
315                int index = rescaleIndex(streams[i].mIndex, STREAM_VOLUME_ALIAS[i], i);
316                streams[i].mIndex = streams[i].getValidIndex(index);
317                setStreamVolumeIndex(i, index);
318                index = rescaleIndex(streams[i].mLastAudibleIndex, STREAM_VOLUME_ALIAS[i], i);
319                streams[i].mLastAudibleIndex = streams[i].getValidIndex(index);
320            }
321        }
322    }
323
324    private void readPersistedSettings() {
325        final ContentResolver cr = mContentResolver;
326
327        mRingerMode = System.getInt(cr, System.MODE_RINGER, AudioManager.RINGER_MODE_NORMAL);
328
329        mVibrateSetting = System.getInt(cr, System.VIBRATE_ON, 0);
330
331        mRingerModeAffectedStreams = Settings.System.getInt(cr,
332                Settings.System.MODE_RINGER_STREAMS_AFFECTED,
333                ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)|
334                 (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED)));
335
336        mMuteAffectedStreams = System.getInt(cr,
337                System.MUTE_STREAMS_AFFECTED,
338                ((1 << AudioSystem.STREAM_MUSIC)|(1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_SYSTEM)));
339
340        mNotificationsUseRingVolume = System.getInt(cr,
341                Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 1);
342
343        if (mNotificationsUseRingVolume == 1) {
344            STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING;
345        }
346        // Each stream will read its own persisted settings
347
348        // Broadcast the sticky intent
349        broadcastRingerMode();
350
351        // Broadcast vibrate settings
352        broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);
353        broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION);
354    }
355
356    private void setStreamVolumeIndex(int stream, int index) {
357        AudioSystem.setStreamVolumeIndex(stream, (index + 5)/10);
358    }
359
360    private int rescaleIndex(int index, int srcStream, int dstStream) {
361        return (index * mStreamStates[dstStream].getMaxIndex() + mStreamStates[srcStream].getMaxIndex() / 2) / mStreamStates[srcStream].getMaxIndex();
362    }
363
364    ///////////////////////////////////////////////////////////////////////////
365    // IPC methods
366    ///////////////////////////////////////////////////////////////////////////
367
368    /** @see AudioManager#adjustVolume(int, int) */
369    public void adjustVolume(int direction, int flags) {
370        adjustSuggestedStreamVolume(direction, AudioManager.USE_DEFAULT_STREAM_TYPE, flags);
371    }
372
373    /** @see AudioManager#adjustVolume(int, int, int) */
374    public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) {
375
376        int streamType = getActiveStreamType(suggestedStreamType);
377
378        // Don't play sound on other streams
379        if (streamType != AudioSystem.STREAM_RING && (flags & AudioManager.FLAG_PLAY_SOUND) != 0) {
380            flags &= ~AudioManager.FLAG_PLAY_SOUND;
381        }
382
383        adjustStreamVolume(streamType, direction, flags);
384    }
385
386    /** @see AudioManager#adjustStreamVolume(int, int, int) */
387    public void adjustStreamVolume(int streamType, int direction, int flags) {
388        ensureValidDirection(direction);
389        ensureValidStreamType(streamType);
390
391
392        VolumeStreamState streamState = mStreamStates[STREAM_VOLUME_ALIAS[streamType]];
393        final int oldIndex = streamState.mIndex;
394        boolean adjustVolume = true;
395
396        // If either the client forces allowing ringer modes for this adjustment,
397        // or the stream type is one that is affected by ringer modes
398        if ((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0
399                || streamType == AudioSystem.STREAM_RING) {
400            // Check if the ringer mode changes with this volume adjustment. If
401            // it does, it will handle adjusting the volume, so we won't below
402            adjustVolume = checkForRingerModeChange(oldIndex, direction);
403        }
404
405        if (adjustVolume && streamState.adjustIndex(direction)) {
406            // Post message to set system volume (it in turn will post a message
407            // to persist). Do not change volume if stream is muted.
408            if (streamState.muteCount() == 0) {
409                sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, STREAM_VOLUME_ALIAS[streamType], SENDMSG_NOOP, 0, 0,
410                        streamState, 0);
411            }
412        }
413
414        // UI
415        mVolumePanel.postVolumeChanged(streamType, flags);
416        // Broadcast Intent
417        sendVolumeUpdate(streamType, oldIndex, streamState.mIndex);
418    }
419
420    /** @see AudioManager#setStreamVolume(int, int, int) */
421    public void setStreamVolume(int streamType, int index, int flags) {
422        ensureValidStreamType(streamType);
423
424        final int oldIndex = mStreamStates[STREAM_VOLUME_ALIAS[streamType]].mIndex;
425
426        index = rescaleIndex(index * 10, streamType, STREAM_VOLUME_ALIAS[streamType]);
427        setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, false, true);
428
429        // UI, etc.
430        mVolumePanel.postVolumeChanged(streamType, flags);
431        // Broadcast Intent
432        sendVolumeUpdate(streamType, oldIndex, index);
433    }
434
435    private void sendVolumeUpdate(int streamType, int oldIndex, int index) {
436        oldIndex = (oldIndex + 5) / 10;
437        index = (index + 5) / 10;
438
439        Intent intent = new Intent(AudioManager.VOLUME_CHANGED_ACTION);
440        intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, streamType);
441        intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, index);
442        intent.putExtra(AudioManager.EXTRA_PREV_VOLUME_STREAM_VALUE, oldIndex);
443
444        mContext.sendBroadcast(intent);
445    }
446
447    /**
448     * Sets the stream state's index, and posts a message to set system volume.
449     * This will not call out to the UI. Assumes a valid stream type.
450     *
451     * @param streamType Type of the stream
452     * @param index Desired volume index of the stream
453     * @param force If true, set the volume even if the desired volume is same
454     * as the current volume.
455     * @param lastAudible If true, stores new index as last audible one
456     */
457    private void setStreamVolumeInt(int streamType, int index, boolean force, boolean lastAudible) {
458        VolumeStreamState streamState = mStreamStates[streamType];
459        if (streamState.setIndex(index, lastAudible) || force) {
460            // Post message to set system volume (it in turn will post a message
461            // to persist).
462            // If stream is muted or we are in silent mode and stream is affected by ringer mode
463            // and the new volume is not 0, just persist the new volume but do not change
464            // current value
465            if (streamState.muteCount() == 0 &&
466                (mRingerMode == AudioManager.RINGER_MODE_NORMAL ||
467                !isStreamAffectedByRingerMode(streamType) ||
468                index == 0)) {
469                sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, streamType, SENDMSG_NOOP, 0, 0,
470                        streamState, 0);
471            } else {
472                // Post a persist volume msg
473                sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamType,
474                        SENDMSG_REPLACE, 0, 1, streamState, PERSIST_DELAY);
475            }
476        }
477    }
478
479    /** @see AudioManager#setStreamSolo(int, boolean) */
480    public void setStreamSolo(int streamType, boolean state, IBinder cb) {
481        for (int stream = 0; stream < mStreamStates.length; stream++) {
482            if (!isStreamAffectedByMute(stream) || stream == streamType) continue;
483            // Bring back last audible volume
484            mStreamStates[stream].mute(cb, state);
485         }
486    }
487
488    /** @see AudioManager#setStreamMute(int, boolean) */
489    public void setStreamMute(int streamType, boolean state, IBinder cb) {
490        if (isStreamAffectedByMute(streamType)) {
491            mStreamStates[streamType].mute(cb, state);
492        }
493    }
494
495    /** @see AudioManager#getStreamVolume(int) */
496    public int getStreamVolume(int streamType) {
497        ensureValidStreamType(streamType);
498        return (mStreamStates[streamType].mIndex + 5) / 10;
499    }
500
501    /** @see AudioManager#getStreamMaxVolume(int) */
502    public int getStreamMaxVolume(int streamType) {
503        ensureValidStreamType(streamType);
504        return (mStreamStates[streamType].getMaxIndex() + 5) / 10;
505    }
506
507    /** @see AudioManager#getRingerMode() */
508    public int getRingerMode() {
509        return mRingerMode;
510    }
511
512    /** @see AudioManager#setRingerMode(int) */
513    public void setRingerMode(int ringerMode) {
514        synchronized (mSettingsLock) {
515            if (ringerMode != mRingerMode) {
516                setRingerModeInt(ringerMode, true);
517                // Send sticky broadcast
518                broadcastRingerMode();
519            }
520        }
521    }
522
523    private void setRingerModeInt(int ringerMode, boolean persist) {
524        mRingerMode = ringerMode;
525
526        // Adjust volumes via posting message
527        int numStreamTypes = AudioSystem.getNumStreamTypes();
528        if (mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
529            for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
530                if (!isStreamAffectedByRingerMode(streamType)) continue;
531                // Bring back last audible volume
532                setStreamVolumeInt(streamType, mStreamStates[streamType].mLastAudibleIndex,
533                                   true, false);
534            }
535        } else {
536            for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
537                if (isStreamAffectedByRingerMode(streamType)) {
538                    // Either silent or vibrate, either way volume is 0
539                    setStreamVolumeInt(streamType, 0, false, false);
540                } else {
541                    // restore stream volume in the case the stream changed from affected
542                    // to non affected by ringer mode. Does not arm to do it for streams that
543                    // are not affected as well.
544                    setStreamVolumeInt(streamType, mStreamStates[streamType].mLastAudibleIndex,
545                            true, false);
546                }
547            }
548        }
549
550        // Post a persist ringer mode msg
551        if (persist) {
552            sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE, SHARED_MSG,
553                    SENDMSG_REPLACE, 0, 0, null, PERSIST_DELAY);
554        }
555    }
556
557    /** @see AudioManager#shouldVibrate(int) */
558    public boolean shouldVibrate(int vibrateType) {
559
560        switch (getVibrateSetting(vibrateType)) {
561
562            case AudioManager.VIBRATE_SETTING_ON:
563                return mRingerMode != AudioManager.RINGER_MODE_SILENT;
564
565            case AudioManager.VIBRATE_SETTING_ONLY_SILENT:
566                return mRingerMode == AudioManager.RINGER_MODE_VIBRATE;
567
568            case AudioManager.VIBRATE_SETTING_OFF:
569                // Phone ringer should always vibrate in vibrate mode
570                if (vibrateType == AudioManager.VIBRATE_TYPE_RINGER) {
571                    return mRingerMode == AudioManager.RINGER_MODE_VIBRATE;
572                }
573
574            default:
575                return false;
576        }
577    }
578
579    /** @see AudioManager#getVibrateSetting(int) */
580    public int getVibrateSetting(int vibrateType) {
581        return (mVibrateSetting >> (vibrateType * 2)) & 3;
582    }
583
584    /** @see AudioManager#setVibrateSetting(int, int) */
585    public void setVibrateSetting(int vibrateType, int vibrateSetting) {
586
587        mVibrateSetting = getValueForVibrateSetting(mVibrateSetting, vibrateType, vibrateSetting);
588
589        // Broadcast change
590        broadcastVibrateSetting(vibrateType);
591
592        // Post message to set ringer mode (it in turn will post a message
593        // to persist)
594        sendMsg(mAudioHandler, MSG_PERSIST_VIBRATE_SETTING, SHARED_MSG, SENDMSG_NOOP, 0, 0,
595                null, 0);
596    }
597
598    /**
599     * @see #setVibrateSetting(int, int)
600     */
601    public static int getValueForVibrateSetting(int existingValue, int vibrateType,
602            int vibrateSetting) {
603
604        // First clear the existing setting. Each vibrate type has two bits in
605        // the value. Note '3' is '11' in binary.
606        existingValue &= ~(3 << (vibrateType * 2));
607
608        // Set into the old value
609        existingValue |= (vibrateSetting & 3) << (vibrateType * 2);
610
611        return existingValue;
612    }
613
614    private class SetModeDeathHandler implements IBinder.DeathRecipient {
615        private IBinder mCb; // To be notified of client's death
616        private int mMode = AudioSystem.MODE_NORMAL; // Current mode set by this client
617
618        SetModeDeathHandler(IBinder cb) {
619            mCb = cb;
620        }
621
622        public void binderDied() {
623            synchronized(mSetModeDeathHandlers) {
624                Log.w(TAG, "setMode() client died");
625                int index = mSetModeDeathHandlers.indexOf(this);
626                if (index < 0) {
627                    Log.w(TAG, "unregistered setMode() client died");
628                } else {
629                    mSetModeDeathHandlers.remove(this);
630                    // If dead client was a the top of client list,
631                    // apply next mode in the stack
632                    if (index == 0) {
633                        // mSetModeDeathHandlers is never empty as the initial entry
634                        // created when AudioService starts is never removed
635                        SetModeDeathHandler hdlr = mSetModeDeathHandlers.get(0);
636                        int mode = hdlr.getMode();
637                        if (AudioService.this.mMode != mode) {
638                            if (AudioSystem.setPhoneState(mode) == AudioSystem.AUDIO_STATUS_OK) {
639                                AudioService.this.mMode = mode;
640                            }
641                        }
642                    }
643                }
644            }
645        }
646
647        public void setMode(int mode) {
648            mMode = mode;
649        }
650
651        public int getMode() {
652            return mMode;
653        }
654
655        public IBinder getBinder() {
656            return mCb;
657        }
658    }
659
660    /** @see AudioManager#setMode(int) */
661    public void setMode(int mode, IBinder cb) {
662        if (!checkAudioSettingsPermission("setMode()")) {
663            return;
664        }
665
666        if (mode < AudioSystem.MODE_CURRENT || mode > AudioSystem.MODE_IN_CALL) {
667            return;
668        }
669
670        synchronized (mSettingsLock) {
671            if (mode == AudioSystem.MODE_CURRENT) {
672                mode = mMode;
673            }
674            if (mode != mMode) {
675                if (AudioSystem.setPhoneState(mode) == AudioSystem.AUDIO_STATUS_OK) {
676                    mMode = mode;
677
678                    synchronized(mSetModeDeathHandlers) {
679                        SetModeDeathHandler hdlr = null;
680                        Iterator iter = mSetModeDeathHandlers.iterator();
681                        while (iter.hasNext()) {
682                            SetModeDeathHandler h = (SetModeDeathHandler)iter.next();
683                            if (h.getBinder() == cb) {
684                                hdlr = h;
685                                // Remove from client list so that it is re-inserted at top of list
686                                iter.remove();
687                                break;
688                            }
689                        }
690                        if (hdlr == null) {
691                            hdlr = new SetModeDeathHandler(cb);
692                            // cb is null when setMode() is called by AudioService constructor
693                            if (cb != null) {
694                                // Register for client death notification
695                                try {
696                                    cb.linkToDeath(hdlr, 0);
697                                } catch (RemoteException e) {
698                                    // Client has died!
699                                    Log.w(TAG, "setMode() could not link to "+cb+" binder death");
700                                }
701                            }
702                        }
703                        // Last client to call setMode() is always at top of client list
704                        // as required by SetModeDeathHandler.binderDied()
705                        mSetModeDeathHandlers.add(0, hdlr);
706                        hdlr.setMode(mode);
707                    }
708                }
709            }
710            int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
711            int index = mStreamStates[STREAM_VOLUME_ALIAS[streamType]].mIndex;
712            setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, true, true);
713        }
714    }
715
716    /** @see AudioManager#getMode() */
717    public int getMode() {
718        return mMode;
719    }
720
721    /** @see AudioManager#playSoundEffect(int) */
722    public void playSoundEffect(int effectType) {
723        sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP,
724                effectType, -1, null, 0);
725    }
726
727    /** @see AudioManager#playSoundEffect(int, float) */
728    public void playSoundEffectVolume(int effectType, float volume) {
729        loadSoundEffects();
730        sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP,
731                effectType, (int) (volume * 1000), null, 0);
732    }
733
734    /**
735     * Loads samples into the soundpool.
736     * This method must be called at when sound effects are enabled
737     */
738    public boolean loadSoundEffects() {
739        synchronized (mSoundEffectsLock) {
740            if (mSoundPool != null) {
741                return true;
742            }
743            mSoundPool = new SoundPool(NUM_SOUNDPOOL_CHANNELS, AudioSystem.STREAM_SYSTEM, 0);
744            if (mSoundPool == null) {
745                return false;
746            }
747            /*
748             * poolId table: The value -1 in this table indicates that corresponding
749             * file (same index in SOUND_EFFECT_FILES[] has not been loaded.
750             * Once loaded, the value in poolId is the sample ID and the same
751             * sample can be reused for another effect using the same file.
752             */
753            int[] poolId = new int[SOUND_EFFECT_FILES.length];
754            for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) {
755                poolId[fileIdx] = -1;
756            }
757            /*
758             * Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded.
759             * If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0:
760             * this indicates we have a valid sample loaded for this effect.
761             */
762            for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
763                // Do not load sample if this effect uses the MediaPlayer
764                if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) {
765                    continue;
766                }
767                if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) {
768                    String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effect][0]];
769                    int sampleId = mSoundPool.load(filePath, 0);
770                    SOUND_EFFECT_FILES_MAP[effect][1] = sampleId;
771                    poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId;
772                    if (sampleId <= 0) {
773                        Log.w(TAG, "Soundpool could not load file: "+filePath);
774                    }
775                } else {
776                    SOUND_EFFECT_FILES_MAP[effect][1] = poolId[SOUND_EFFECT_FILES_MAP[effect][0]];
777                }
778            }
779        }
780
781        return true;
782    }
783
784    /**
785     *  Unloads samples from the sound pool.
786     *  This method can be called to free some memory when
787     *  sound effects are disabled.
788     */
789    public void unloadSoundEffects() {
790        synchronized (mSoundEffectsLock) {
791            if (mSoundPool == null) {
792                return;
793            }
794            int[] poolId = new int[SOUND_EFFECT_FILES.length];
795            for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) {
796                poolId[fileIdx] = 0;
797            }
798
799            for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
800                if (SOUND_EFFECT_FILES_MAP[effect][1] <= 0) {
801                    continue;
802                }
803                if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == 0) {
804                    mSoundPool.unload(SOUND_EFFECT_FILES_MAP[effect][1]);
805                    SOUND_EFFECT_FILES_MAP[effect][1] = -1;
806                    poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1;
807                }
808            }
809            mSoundPool = null;
810        }
811    }
812
813    /** @see AudioManager#reloadAudioSettings() */
814    public void reloadAudioSettings() {
815        // restore ringer mode, ringer mode affected streams, mute affected streams and vibrate settings
816        readPersistedSettings();
817
818        // restore volume settings
819        int numStreamTypes = AudioSystem.getNumStreamTypes();
820        for (int streamType = 0; streamType < numStreamTypes; streamType++) {
821            VolumeStreamState streamState = mStreamStates[streamType];
822
823            String settingName = System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[streamType]];
824            String lastAudibleSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE;
825            int index = Settings.System.getInt(mContentResolver,
826                                           settingName,
827                                           AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
828            if (STREAM_VOLUME_ALIAS[streamType] != streamType) {
829                index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType);
830            } else {
831                index *= 10;
832            }
833            streamState.mIndex = streamState.getValidIndex(index);
834
835            index = (index + 5) / 10;
836            index = Settings.System.getInt(mContentResolver,
837                                            lastAudibleSettingName,
838                                            (index > 0) ? index : AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
839            if (STREAM_VOLUME_ALIAS[streamType] != streamType) {
840                index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType);
841            } else {
842                index *= 10;
843            }
844            streamState.mLastAudibleIndex = streamState.getValidIndex(index);
845
846            // unmute stream that whas muted but is not affect by mute anymore
847            if (streamState.muteCount() != 0 && !isStreamAffectedByMute(streamType)) {
848                int size = streamState.mDeathHandlers.size();
849                for (int i = 0; i < size; i++) {
850                    streamState.mDeathHandlers.get(i).mMuteCount = 1;
851                    streamState.mDeathHandlers.get(i).mute(false);
852                }
853            }
854            // apply stream volume
855            if (streamState.muteCount() == 0) {
856                setStreamVolumeIndex(streamType, streamState.mIndex);
857            }
858        }
859
860        // apply new ringer mode
861        setRingerModeInt(getRingerMode(), false);
862    }
863
864    /** @see AudioManager#setSpeakerphoneOn() */
865    public void setSpeakerphoneOn(boolean on){
866        if (!checkAudioSettingsPermission("setSpeakerphoneOn()")) {
867            return;
868        }
869        if (on) {
870            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_SPEAKER);
871            mForcedUseForComm = AudioSystem.FORCE_SPEAKER;
872        } else {
873            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_NONE);
874            mForcedUseForComm = AudioSystem.FORCE_NONE;
875        }
876    }
877
878    /** @see AudioManager#isSpeakerphoneOn() */
879    public boolean isSpeakerphoneOn() {
880        if (mForcedUseForComm == AudioSystem.FORCE_SPEAKER) {
881            return true;
882        } else {
883            return false;
884        }
885    }
886
887    /** @see AudioManager#setBluetoothScoOn() */
888    public void setBluetoothScoOn(boolean on){
889        if (!checkAudioSettingsPermission("setBluetoothScoOn()")) {
890            return;
891        }
892        if (on) {
893            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_BT_SCO);
894            AudioSystem.setForceUse(AudioSystem.FOR_RECORD, AudioSystem.FORCE_BT_SCO);
895            mForcedUseForComm = AudioSystem.FORCE_BT_SCO;
896        } else {
897            AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_NONE);
898            AudioSystem.setForceUse(AudioSystem.FOR_RECORD, AudioSystem.FORCE_NONE);
899            mForcedUseForComm = AudioSystem.FORCE_NONE;
900        }
901    }
902
903    /** @see AudioManager#isBluetoothScoOn() */
904    public boolean isBluetoothScoOn() {
905        if (mForcedUseForComm == AudioSystem.FORCE_BT_SCO) {
906            return true;
907        } else {
908            return false;
909        }
910    }
911
912
913    ///////////////////////////////////////////////////////////////////////////
914    // Internal methods
915    ///////////////////////////////////////////////////////////////////////////
916
917    /**
918     * Checks if the adjustment should change ringer mode instead of just
919     * adjusting volume. If so, this will set the proper ringer mode and volume
920     * indices on the stream states.
921     */
922    private boolean checkForRingerModeChange(int oldIndex, int direction) {
923        boolean adjustVolumeIndex = true;
924        int newRingerMode = mRingerMode;
925
926        if (mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
927            // audible mode, at the bottom of the scale
928            if (direction == AudioManager.ADJUST_LOWER
929                    && (oldIndex + 5) / 10 == 1) {
930                // "silent mode", but which one?
931                newRingerMode = System.getInt(mContentResolver, System.VIBRATE_IN_SILENT, 1) == 1
932                    ? AudioManager.RINGER_MODE_VIBRATE
933                    : AudioManager.RINGER_MODE_SILENT;
934            }
935        } else {
936            if (direction == AudioManager.ADJUST_RAISE) {
937                // exiting silent mode
938                newRingerMode = AudioManager.RINGER_MODE_NORMAL;
939            }
940        }
941
942        if (newRingerMode != mRingerMode) {
943            setRingerMode(newRingerMode);
944
945            /*
946             * If we are changing ringer modes, do not increment/decrement the
947             * volume index. Instead, the handler for the message above will
948             * take care of changing the index.
949             */
950            adjustVolumeIndex = false;
951        }
952
953        return adjustVolumeIndex;
954    }
955
956    public boolean isStreamAffectedByRingerMode(int streamType) {
957        return (mRingerModeAffectedStreams & (1 << streamType)) != 0;
958    }
959
960    public boolean isStreamAffectedByMute(int streamType) {
961        return (mMuteAffectedStreams & (1 << streamType)) != 0;
962    }
963
964    private void ensureValidDirection(int direction) {
965        if (direction < AudioManager.ADJUST_LOWER || direction > AudioManager.ADJUST_RAISE) {
966            throw new IllegalArgumentException("Bad direction " + direction);
967        }
968    }
969
970    private void ensureValidStreamType(int streamType) {
971        if (streamType < 0 || streamType >= mStreamStates.length) {
972            throw new IllegalArgumentException("Bad stream type " + streamType);
973        }
974    }
975
976    private int getActiveStreamType(int suggestedStreamType) {
977        boolean isOffhook = false;
978        try {
979            ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
980            if (phone != null) isOffhook = phone.isOffhook();
981        } catch (RemoteException e) {
982            Log.w(TAG, "Couldn't connect to phone service", e);
983        }
984
985        if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION) == AudioSystem.FORCE_BT_SCO) {
986            // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO...");
987            return AudioSystem.STREAM_BLUETOOTH_SCO;
988        } else if (isOffhook || AudioSystem.isStreamActive(AudioSystem.STREAM_VOICE_CALL)) {
989            // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL...");
990            return AudioSystem.STREAM_VOICE_CALL;
991        } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC)) {
992            // Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC...");
993            return AudioSystem.STREAM_MUSIC;
994        } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
995            // Log.v(TAG, "getActiveStreamType: Forcing STREAM_RING...");
996            return AudioSystem.STREAM_RING;
997        } else {
998            // Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType);
999            return suggestedStreamType;
1000        }
1001    }
1002
1003    private void broadcastRingerMode() {
1004        // Send sticky broadcast
1005        Intent broadcast = new Intent(AudioManager.RINGER_MODE_CHANGED_ACTION);
1006        broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, mRingerMode);
1007        broadcast.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
1008                | Intent.FLAG_RECEIVER_REPLACE_PENDING);
1009        long origCallerIdentityToken = Binder.clearCallingIdentity();
1010        mContext.sendStickyBroadcast(broadcast);
1011        Binder.restoreCallingIdentity(origCallerIdentityToken);
1012    }
1013
1014    private void broadcastVibrateSetting(int vibrateType) {
1015        // Send broadcast
1016        if (ActivityManagerNative.isSystemReady()) {
1017            Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION);
1018            broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType);
1019            broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType));
1020            mContext.sendBroadcast(broadcast);
1021        }
1022    }
1023
1024    // Message helper methods
1025    private static int getMsg(int baseMsg, int streamType) {
1026        return (baseMsg & 0xffff) | streamType << 16;
1027    }
1028
1029    private static int getMsgBase(int msg) {
1030        return msg & 0xffff;
1031    }
1032
1033    private static void sendMsg(Handler handler, int baseMsg, int streamType,
1034            int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) {
1035        int msg = (streamType == SHARED_MSG) ? baseMsg : getMsg(baseMsg, streamType);
1036
1037        if (existingMsgPolicy == SENDMSG_REPLACE) {
1038            handler.removeMessages(msg);
1039        } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) {
1040            return;
1041        }
1042
1043        handler
1044                .sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delay);
1045    }
1046
1047    boolean checkAudioSettingsPermission(String method) {
1048        if (mContext.checkCallingOrSelfPermission("android.permission.MODIFY_AUDIO_SETTINGS")
1049                == PackageManager.PERMISSION_GRANTED) {
1050            return true;
1051        }
1052        String msg = "Audio Settings Permission Denial: " + method + " from pid="
1053                + Binder.getCallingPid()
1054                + ", uid=" + Binder.getCallingUid();
1055        Log.w(TAG, msg);
1056        return false;
1057    }
1058
1059
1060    ///////////////////////////////////////////////////////////////////////////
1061    // Inner classes
1062    ///////////////////////////////////////////////////////////////////////////
1063
1064    public class VolumeStreamState {
1065        private final int mStreamType;
1066
1067        private String mVolumeIndexSettingName;
1068        private String mLastAudibleVolumeIndexSettingName;
1069        private int mIndexMax;
1070        private int mIndex;
1071        private int mLastAudibleIndex;
1072        private ArrayList<VolumeDeathHandler> mDeathHandlers; //handles mute/solo requests client death
1073
1074        private VolumeStreamState(String settingName, int streamType) {
1075
1076            setVolumeIndexSettingName(settingName);
1077
1078            mStreamType = streamType;
1079
1080            final ContentResolver cr = mContentResolver;
1081            mIndexMax = MAX_STREAM_VOLUME[streamType];
1082            mIndex = Settings.System.getInt(cr,
1083                                            mVolumeIndexSettingName,
1084                                            AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1085            mLastAudibleIndex = Settings.System.getInt(cr,
1086                                                       mLastAudibleVolumeIndexSettingName,
1087                                                       (mIndex > 0) ? mIndex : AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1088            AudioSystem.initStreamVolume(streamType, 0, mIndexMax);
1089            mIndexMax *= 10;
1090            mIndex = getValidIndex(10 * mIndex);
1091            mLastAudibleIndex = getValidIndex(10 * mLastAudibleIndex);
1092            setStreamVolumeIndex(streamType, mIndex);
1093            mDeathHandlers = new ArrayList<VolumeDeathHandler>();
1094        }
1095
1096        public void setVolumeIndexSettingName(String settingName) {
1097            mVolumeIndexSettingName = settingName;
1098            mLastAudibleVolumeIndexSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE;
1099        }
1100
1101        public boolean adjustIndex(int deltaIndex) {
1102            return setIndex(mIndex + deltaIndex * 10, true);
1103        }
1104
1105        public boolean setIndex(int index, boolean lastAudible) {
1106            int oldIndex = mIndex;
1107            mIndex = getValidIndex(index);
1108
1109            if (oldIndex != mIndex) {
1110                if (lastAudible) {
1111                    mLastAudibleIndex = mIndex;
1112                }
1113                // Apply change to all streams using this one as alias
1114                int numStreamTypes = AudioSystem.getNumStreamTypes();
1115                for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
1116                    if (streamType != mStreamType && STREAM_VOLUME_ALIAS[streamType] == mStreamType) {
1117                        mStreamStates[streamType].setIndex(rescaleIndex(mIndex, mStreamType, streamType), lastAudible);
1118                    }
1119                }
1120                return true;
1121            } else {
1122                return false;
1123            }
1124        }
1125
1126        public int getMaxIndex() {
1127            return mIndexMax;
1128        }
1129
1130        public void mute(IBinder cb, boolean state) {
1131            VolumeDeathHandler handler = getDeathHandler(cb, state);
1132            if (handler == null) {
1133                Log.e(TAG, "Could not get client death handler for stream: "+mStreamType);
1134                return;
1135            }
1136            handler.mute(state);
1137        }
1138
1139        private int getValidIndex(int index) {
1140            if (index < 0) {
1141                return 0;
1142            } else if (index > mIndexMax) {
1143                return mIndexMax;
1144            }
1145
1146            return index;
1147        }
1148
1149        private class VolumeDeathHandler implements IBinder.DeathRecipient {
1150            private IBinder mICallback; // To be notified of client's death
1151            private int mMuteCount; // Number of active mutes for this client
1152
1153            VolumeDeathHandler(IBinder cb) {
1154                mICallback = cb;
1155            }
1156
1157            public void mute(boolean state) {
1158                synchronized(mDeathHandlers) {
1159                    if (state) {
1160                        if (mMuteCount == 0) {
1161                            // Register for client death notification
1162                            try {
1163                                mICallback.linkToDeath(this, 0);
1164                                mDeathHandlers.add(this);
1165                                // If the stream is not yet muted by any client, set lvel to 0
1166                                if (muteCount() == 0) {
1167                                    setIndex(0, false);
1168                                    sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0,
1169                                            VolumeStreamState.this, 0);
1170                                }
1171                            } catch (RemoteException e) {
1172                                // Client has died!
1173                                binderDied();
1174                                mDeathHandlers.notify();
1175                                return;
1176                            }
1177                        } else {
1178                            Log.w(TAG, "stream: "+mStreamType+" was already muted by this client");
1179                        }
1180                        mMuteCount++;
1181                    } else {
1182                        if (mMuteCount == 0) {
1183                            Log.e(TAG, "unexpected unmute for stream: "+mStreamType);
1184                        } else {
1185                            mMuteCount--;
1186                            if (mMuteCount == 0) {
1187                                // Unregistr from client death notification
1188                                mDeathHandlers.remove(this);
1189                                mICallback.unlinkToDeath(this, 0);
1190                                if (muteCount() == 0) {
1191                                    // If the stream is not mut any more, restore it's volume if
1192                                    // ringer mode allows it
1193                                    if (!isStreamAffectedByRingerMode(mStreamType) || mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
1194                                        setIndex(mLastAudibleIndex, false);
1195                                        sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0,
1196                                                VolumeStreamState.this, 0);
1197                                    }
1198                                }
1199                            }
1200                        }
1201                    }
1202                    mDeathHandlers.notify();
1203                }
1204            }
1205
1206            public void binderDied() {
1207                Log.w(TAG, "Volume service client died for stream: "+mStreamType);
1208                if (mMuteCount != 0) {
1209                    // Reset all active mute requests from this client.
1210                    mMuteCount = 1;
1211                    mute(false);
1212                }
1213            }
1214        }
1215
1216        private int muteCount() {
1217            int count = 0;
1218            int size = mDeathHandlers.size();
1219            for (int i = 0; i < size; i++) {
1220                count += mDeathHandlers.get(i).mMuteCount;
1221            }
1222            return count;
1223        }
1224
1225        private VolumeDeathHandler getDeathHandler(IBinder cb, boolean state) {
1226            synchronized(mDeathHandlers) {
1227                VolumeDeathHandler handler;
1228                int size = mDeathHandlers.size();
1229                for (int i = 0; i < size; i++) {
1230                    handler = mDeathHandlers.get(i);
1231                    if (cb.equals(handler.mICallback)) {
1232                        return handler;
1233                    }
1234                }
1235                // If this is the first mute request for this client, create a new
1236                // client death handler. Otherwise, it is an out of sequence unmute request.
1237                if (state) {
1238                    handler = new VolumeDeathHandler(cb);
1239                } else {
1240                    Log.w(TAG, "stream was not muted by this client");
1241                    handler = null;
1242                }
1243                return handler;
1244            }
1245        }
1246    }
1247
1248    /** Thread that handles native AudioSystem control. */
1249    private class AudioSystemThread extends Thread {
1250        AudioSystemThread() {
1251            super("AudioService");
1252        }
1253
1254        @Override
1255        public void run() {
1256            // Set this thread up so the handler will work on it
1257            Looper.prepare();
1258
1259            synchronized(AudioService.this) {
1260                mAudioHandler = new AudioHandler();
1261
1262                // Notify that the handler has been created
1263                AudioService.this.notify();
1264            }
1265
1266            // Listen for volume change requests that are set by VolumePanel
1267            Looper.loop();
1268        }
1269    }
1270
1271    /** Handles internal volume messages in separate volume thread. */
1272    private class AudioHandler extends Handler {
1273
1274        private void setSystemVolume(VolumeStreamState streamState) {
1275
1276            // Adjust volume
1277            setStreamVolumeIndex(streamState.mStreamType, streamState.mIndex);
1278
1279            // Apply change to all streams using this one as alias
1280            int numStreamTypes = AudioSystem.getNumStreamTypes();
1281            for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
1282                if (streamType != streamState.mStreamType &&
1283                    STREAM_VOLUME_ALIAS[streamType] == streamState.mStreamType) {
1284                    setStreamVolumeIndex(streamType, mStreamStates[streamType].mIndex);
1285                }
1286            }
1287
1288            // Post a persist volume msg
1289            sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamState.mStreamType,
1290                    SENDMSG_REPLACE, 1, 1, streamState, PERSIST_DELAY);
1291        }
1292
1293        private void persistVolume(VolumeStreamState streamState, boolean current, boolean lastAudible) {
1294            if (current) {
1295                System.putInt(mContentResolver, streamState.mVolumeIndexSettingName,
1296                              (streamState.mIndex + 5)/ 10);
1297            }
1298            if (lastAudible) {
1299                System.putInt(mContentResolver, streamState.mLastAudibleVolumeIndexSettingName,
1300                    (streamState.mLastAudibleIndex + 5) / 10);
1301            }
1302        }
1303
1304        private void persistRingerMode() {
1305            System.putInt(mContentResolver, System.MODE_RINGER, mRingerMode);
1306        }
1307
1308        private void persistVibrateSetting() {
1309            System.putInt(mContentResolver, System.VIBRATE_ON, mVibrateSetting);
1310        }
1311
1312        private void playSoundEffect(int effectType, int volume) {
1313            synchronized (mSoundEffectsLock) {
1314                if (mSoundPool == null) {
1315                    return;
1316                }
1317                float volFloat;
1318                // use STREAM_MUSIC volume attenuated by 3 dB if volume is not specified by caller
1319                if (volume < 0) {
1320                    // Same linear to log conversion as in native AudioSystem::linearToLog() (AudioSystem.cpp)
1321                    float dBPerStep = (float)((0.5 * 100) / MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]);
1322                    int musicVolIndex = (mStreamStates[AudioSystem.STREAM_MUSIC].mIndex + 5) / 10;
1323                    float musicVoldB = dBPerStep * (musicVolIndex - MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]);
1324                    volFloat = (float)Math.pow(10, (musicVoldB - 3)/20);
1325                } else {
1326                    volFloat = (float) volume / 1000.0f;
1327                }
1328
1329                if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) {
1330                    mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1], volFloat, volFloat, 0, 0, 1.0f);
1331                } else {
1332                    MediaPlayer mediaPlayer = new MediaPlayer();
1333                    if (mediaPlayer != null) {
1334                        try {
1335                            String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effectType][0]];
1336                            mediaPlayer.setDataSource(filePath);
1337                            mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM);
1338                            mediaPlayer.prepare();
1339                            mediaPlayer.setVolume(volFloat, volFloat);
1340                            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
1341                                public void onCompletion(MediaPlayer mp) {
1342                                    cleanupPlayer(mp);
1343                                }
1344                            });
1345                            mediaPlayer.setOnErrorListener(new OnErrorListener() {
1346                                public boolean onError(MediaPlayer mp, int what, int extra) {
1347                                    cleanupPlayer(mp);
1348                                    return true;
1349                                }
1350                            });
1351                            mediaPlayer.start();
1352                        } catch (IOException ex) {
1353                            Log.w(TAG, "MediaPlayer IOException: "+ex);
1354                        } catch (IllegalArgumentException ex) {
1355                            Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex);
1356                        } catch (IllegalStateException ex) {
1357                            Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
1358                        }
1359                    }
1360                }
1361            }
1362        }
1363
1364        private void cleanupPlayer(MediaPlayer mp) {
1365            if (mp != null) {
1366                try {
1367                    mp.stop();
1368                    mp.release();
1369                } catch (IllegalStateException ex) {
1370                    Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
1371                }
1372            }
1373        }
1374
1375        @Override
1376        public void handleMessage(Message msg) {
1377            int baseMsgWhat = getMsgBase(msg.what);
1378
1379            switch (baseMsgWhat) {
1380
1381                case MSG_SET_SYSTEM_VOLUME:
1382                    setSystemVolume((VolumeStreamState) msg.obj);
1383                    break;
1384
1385                case MSG_PERSIST_VOLUME:
1386                    persistVolume((VolumeStreamState) msg.obj, (msg.arg1 != 0), (msg.arg2 != 0));
1387                    break;
1388
1389                case MSG_PERSIST_RINGER_MODE:
1390                    persistRingerMode();
1391                    break;
1392
1393                case MSG_PERSIST_VIBRATE_SETTING:
1394                    persistVibrateSetting();
1395                    break;
1396
1397                case MSG_MEDIA_SERVER_DIED:
1398                    // Force creation of new IAudioflinger interface
1399                    if (!mMediaServerOk) {
1400                        Log.e(TAG, "Media server died.");
1401                        AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC);
1402                        sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
1403                                null, 500);
1404                    }
1405                    break;
1406
1407                case MSG_MEDIA_SERVER_STARTED:
1408                    Log.e(TAG, "Media server started.");
1409                    // Restore device connection states
1410                    Set set = mConnectedDevices.entrySet();
1411                    Iterator i = set.iterator();
1412                    while(i.hasNext()){
1413                        Map.Entry device = (Map.Entry)i.next();
1414                        AudioSystem.setDeviceConnectionState(((Integer)device.getKey()).intValue(),
1415                                                             AudioSystem.DEVICE_STATE_AVAILABLE,
1416                                                             (String)device.getValue());
1417                    }
1418
1419                    // Restore call state
1420                    AudioSystem.setPhoneState(mMode);
1421
1422                    // Restore forced usage for communcations and record
1423                    AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, mForcedUseForComm);
1424                    AudioSystem.setForceUse(AudioSystem.FOR_RECORD, mForcedUseForComm);
1425
1426                    // Restore stream volumes
1427                    int numStreamTypes = AudioSystem.getNumStreamTypes();
1428                    for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
1429                        int index;
1430                        VolumeStreamState streamState = mStreamStates[streamType];
1431                        AudioSystem.initStreamVolume(streamType, 0, (streamState.mIndexMax + 5) / 10);
1432                        if (streamState.muteCount() == 0) {
1433                            index = streamState.mIndex;
1434                        } else {
1435                            index = 0;
1436                        }
1437                        setStreamVolumeIndex(streamType, index);
1438                    }
1439
1440                    // Restore ringer mode
1441                    setRingerModeInt(getRingerMode(), false);
1442                    break;
1443
1444                case MSG_PLAY_SOUND_EFFECT:
1445                    playSoundEffect(msg.arg1, msg.arg2);
1446                    break;
1447            }
1448        }
1449    }
1450
1451    private class SettingsObserver extends ContentObserver {
1452
1453        SettingsObserver() {
1454            super(new Handler());
1455            mContentResolver.registerContentObserver(Settings.System.getUriFor(
1456                Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this);
1457            mContentResolver.registerContentObserver(Settings.System.getUriFor(
1458                    Settings.System.NOTIFICATIONS_USE_RING_VOLUME), false, this);
1459        }
1460
1461        @Override
1462        public void onChange(boolean selfChange) {
1463            super.onChange(selfChange);
1464            synchronized (mSettingsLock) {
1465                int ringerModeAffectedStreams = Settings.System.getInt(mContentResolver,
1466                        Settings.System.MODE_RINGER_STREAMS_AFFECTED,
1467                        0);
1468                if (ringerModeAffectedStreams != mRingerModeAffectedStreams) {
1469                    /*
1470                     * Ensure all stream types that should be affected by ringer mode
1471                     * are in the proper state.
1472                     */
1473                    mRingerModeAffectedStreams = ringerModeAffectedStreams;
1474                    setRingerModeInt(getRingerMode(), false);
1475                }
1476
1477                int notificationsUseRingVolume = Settings.System.getInt(mContentResolver,
1478                        Settings.System.NOTIFICATIONS_USE_RING_VOLUME,
1479                        1);
1480                if (notificationsUseRingVolume != mNotificationsUseRingVolume) {
1481                    mNotificationsUseRingVolume = notificationsUseRingVolume;
1482                    if (mNotificationsUseRingVolume == 1) {
1483                        STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING;
1484                        mStreamStates[AudioSystem.STREAM_NOTIFICATION].setVolumeIndexSettingName(
1485                                System.VOLUME_SETTINGS[AudioSystem.STREAM_RING]);
1486                    } else {
1487                        STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_NOTIFICATION;
1488                        mStreamStates[AudioSystem.STREAM_NOTIFICATION].setVolumeIndexSettingName(
1489                                System.VOLUME_SETTINGS[AudioSystem.STREAM_NOTIFICATION]);
1490                        // Persist notification volume volume as it was not persisted while aliased to ring volume
1491                        //  and persist with no delay as there might be registered observers of the persisted
1492                        //  notification volume.
1493                        sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, AudioSystem.STREAM_NOTIFICATION,
1494                                SENDMSG_REPLACE, 1, 1, mStreamStates[AudioSystem.STREAM_NOTIFICATION], 0);
1495                    }
1496                }
1497            }
1498        }
1499    }
1500
1501    /**
1502     * Receiver for misc intent broadcasts the Phone app cares about.
1503     */
1504    private class AudioServiceBroadcastReceiver extends BroadcastReceiver {
1505        @Override
1506        public void onReceive(Context context, Intent intent) {
1507            String action = intent.getAction();
1508
1509            if (action.equals(Intent.ACTION_DOCK_EVENT)) {
1510                int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
1511                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
1512                int config;
1513                switch (dockState) {
1514                    case Intent.EXTRA_DOCK_STATE_DESK:
1515                        config = AudioSystem.FORCE_BT_DESK_DOCK;
1516                        break;
1517                    case Intent.EXTRA_DOCK_STATE_CAR:
1518                        config = AudioSystem.FORCE_BT_CAR_DOCK;
1519                        break;
1520                    case Intent.EXTRA_DOCK_STATE_UNDOCKED:
1521                    default:
1522                        config = AudioSystem.FORCE_NONE;
1523                }
1524                AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
1525            } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
1526                int state = intent.getIntExtra(BluetoothA2dp.EXTRA_SINK_STATE,
1527                                               BluetoothA2dp.STATE_DISCONNECTED);
1528                BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
1529                String address = btDevice.getAddress();
1530                boolean isConnected = (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP) &&
1531                                       ((String)mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP)).equals(address));
1532
1533                if (isConnected &&
1534                    state != BluetoothA2dp.STATE_CONNECTED && state != BluetoothA2dp.STATE_PLAYING) {
1535                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
1536                            AudioSystem.DEVICE_STATE_UNAVAILABLE,
1537                            address);
1538                    mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
1539                } else if (!isConnected &&
1540                             (state == BluetoothA2dp.STATE_CONNECTED ||
1541                              state == BluetoothA2dp.STATE_PLAYING)) {
1542                    AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
1543                                                         AudioSystem.DEVICE_STATE_AVAILABLE,
1544                                                         address);
1545                    // Reset A2DP suspend state each time a new sink is connected
1546                    AudioSystem.setParameters("A2dpSuspended=false");
1547                    mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP),
1548                            address);
1549                }
1550            } else if (action.equals(BluetoothHeadset.ACTION_STATE_CHANGED)) {
1551                int state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE,
1552                                               BluetoothHeadset.STATE_ERROR);
1553                int device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
1554                BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
1555                String address = null;
1556                if (btDevice != null) {
1557                    address = btDevice.getAddress();
1558                    BluetoothClass btClass = btDevice.getBluetoothClass();
1559                    if (btClass != null) {
1560                        switch (btClass.getDeviceClass()) {
1561                        case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET:
1562                        case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
1563                            device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
1564                            break;
1565                        case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO:
1566                            device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1567                            break;
1568                        }
1569                    }
1570                }
1571
1572                boolean isConnected = (mConnectedDevices.containsKey(device) &&
1573                                       ((String)mConnectedDevices.get(device)).equals(address));
1574
1575                if (isConnected && state != BluetoothHeadset.STATE_CONNECTED) {
1576                    AudioSystem.setDeviceConnectionState(device,
1577                                                         AudioSystem.DEVICE_STATE_UNAVAILABLE,
1578                                                         address);
1579                    mConnectedDevices.remove(device);
1580                } else if (!isConnected && state == BluetoothHeadset.STATE_CONNECTED) {
1581                    AudioSystem.setDeviceConnectionState(device,
1582                                                         AudioSystem.DEVICE_STATE_AVAILABLE,
1583                                                         address);
1584                    mConnectedDevices.put(new Integer(device), address);
1585                }
1586            } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
1587                int state = intent.getIntExtra("state", 0);
1588                int microphone = intent.getIntExtra("microphone", 0);
1589
1590                if (microphone != 0) {
1591                    boolean isConnected = mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADSET);
1592                    if (state == 0 && isConnected) {
1593                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,
1594                                AudioSystem.DEVICE_STATE_UNAVAILABLE,
1595                                "");
1596                        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADSET);
1597                    } else if (state == 1 && !isConnected)  {
1598                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,
1599                                AudioSystem.DEVICE_STATE_AVAILABLE,
1600                                "");
1601                        mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADSET), "");
1602                    }
1603                } else {
1604                    boolean isConnected = mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE);
1605                    if (state == 0 && isConnected) {
1606                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE,
1607                                AudioSystem.DEVICE_STATE_UNAVAILABLE,
1608                                "");
1609                        mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE);
1610                    } else if (state == 1 && !isConnected)  {
1611                        AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE,
1612                                AudioSystem.DEVICE_STATE_AVAILABLE,
1613                                "");
1614                        mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE), "");
1615                    }
1616                }
1617            }
1618        }
1619    }
1620
1621    //==========================================================================================
1622    // AudioFocus
1623    //==========================================================================================
1624    private static class FocusStackEntry {
1625        public int mStreamType = -1;// no stream type
1626        public boolean mIsTransportControlReceiver = false;
1627        public IAudioFocusDispatcher mFocusDispatcher = null;
1628        public IBinder mSourceRef = null;
1629        public String mClientId;
1630        public int mDurationHint;
1631
1632        public FocusStackEntry() {
1633        }
1634
1635        public FocusStackEntry(int streamType, int duration, boolean isTransportControlReceiver,
1636                IAudioFocusDispatcher afl, IBinder source, String id) {
1637            mStreamType = streamType;
1638            mIsTransportControlReceiver = isTransportControlReceiver;
1639            mFocusDispatcher = afl;
1640            mSourceRef = source;
1641            mClientId = id;
1642            mDurationHint = duration;
1643        }
1644    }
1645
1646    private Stack<FocusStackEntry> mFocusStack = new Stack<FocusStackEntry>();
1647
1648    /**
1649     * Helper function:
1650     * Display in the log the current entries in the audio focus stack
1651     */
1652    private void dumpFocusStack(PrintWriter pw) {
1653        pw.println("Audio Focus stack entries:");
1654        synchronized(mFocusStack) {
1655            Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
1656            while(stackIterator.hasNext()) {
1657                FocusStackEntry fse = stackIterator.next();
1658                pw.println("     source:" + fse.mSourceRef + " -- client: " + fse.mClientId
1659                        + " -- duration: " +fse.mDurationHint);
1660            }
1661        }
1662    }
1663
1664    /**
1665     * Helper function:
1666     * Remove a focus listener from the focus stack.
1667     * @param focusListenerToRemove the focus listener
1668     * @param signal if true and the listener was at the top of the focus stack, i.e. it was holding
1669     *   focus, notify the next item in the stack it gained focus.
1670     */
1671    private void removeFocusStackEntry(String clientToRemove, boolean signal) {
1672        // is the current top of the focus stack abandoning focus? (because of death or request)
1673        if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientToRemove))
1674        {
1675            //Log.i(TAG, "   removeFocusStackEntry() removing top of stack");
1676            mFocusStack.pop();
1677            if (signal) {
1678                // notify the new top of the stack it gained focus
1679                if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)
1680                        && canReassignAudioFocus()) {
1681                    try {
1682                        mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange(
1683                                AudioManager.AUDIOFOCUS_GAIN, mFocusStack.peek().mClientId);
1684                    } catch (RemoteException e) {
1685                        Log.e(TAG, " Failure to signal gain of focus due to "+ e);
1686                        e.printStackTrace();
1687                    }
1688                }
1689            }
1690        } else {
1691            // focus is abandoned by a client that's not at the top of the stack,
1692            // no need to update focus.
1693            Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
1694            while(stackIterator.hasNext()) {
1695                FocusStackEntry fse = (FocusStackEntry)stackIterator.next();
1696                if(fse.mClientId.equals(clientToRemove)) {
1697                    Log.i(TAG, " AudioFocus  abandonAudioFocus(): removing entry for "
1698                            + fse.mClientId);
1699                    mFocusStack.remove(fse);
1700                }
1701            }
1702        }
1703    }
1704
1705    /**
1706     * Helper function:
1707     * Remove focus listeners from the focus stack for a particular client.
1708     */
1709    private void removeFocusStackEntryForClient(IBinder cb) {
1710        // focus is abandoned by a client that's not at the top of the stack,
1711        // no need to update focus.
1712        Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
1713        while(stackIterator.hasNext()) {
1714            FocusStackEntry fse = (FocusStackEntry)stackIterator.next();
1715            if(fse.mSourceRef.equals(cb)) {
1716                Log.i(TAG, " AudioFocus  abandonAudioFocus(): removing entry for "
1717                        + fse.mClientId);
1718                mFocusStack.remove(fse);
1719            }
1720        }
1721    }
1722
1723    /**
1724     * Helper function:
1725     * Returns true if the system is in a state where the focus can be reevaluated, false otherwise.
1726     */
1727    private boolean canReassignAudioFocus() {
1728        // focus requests are rejected during a phone call
1729        if (getMode() == AudioSystem.MODE_IN_CALL) {
1730            Log.i(TAG, " AudioFocus  can't be reassigned during a call, exiting");
1731            return false;
1732        }
1733        return true;
1734    }
1735
1736    /**
1737     * Inner class to monitor audio focus client deaths, and remove them from the audio focus
1738     * stack if necessary.
1739     */
1740    private class AudioFocusDeathHandler implements IBinder.DeathRecipient {
1741        private IBinder mCb; // To be notified of client's death
1742
1743        AudioFocusDeathHandler(IBinder cb) {
1744            mCb = cb;
1745        }
1746
1747        public void binderDied() {
1748            synchronized(mFocusStack) {
1749                Log.w(TAG, "  AudioFocus   audio focus client died");
1750                removeFocusStackEntryForClient(mCb);
1751            }
1752        }
1753
1754        public IBinder getBinder() {
1755            return mCb;
1756        }
1757    }
1758
1759
1760    /** @see AudioManager#requestAudioFocus(IAudioFocusDispatcher, int, int) */
1761    public int requestAudioFocus(int mainStreamType, int durationHint, IBinder cb,
1762            IAudioFocusDispatcher fd, String clientId) {
1763        Log.i(TAG, " AudioFocus  requestAudioFocus() from " + clientId);
1764        // the main stream type for the audio focus request is currently not used. It may
1765        // potentially be used to handle multiple stream type-dependent audio focuses.
1766
1767        if ((cb == null) || !cb.pingBinder()) {
1768            Log.i(TAG, " AudioFocus  DOA client for requestAudioFocus(), exiting");
1769            return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
1770        }
1771
1772        if (!canReassignAudioFocus()) {
1773            return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
1774        }
1775
1776        synchronized(mFocusStack) {
1777            if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientId)) {
1778                mFocusStack.peek().mDurationHint = durationHint;
1779                // if focus is already owned by this client, don't do anything
1780                return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
1781            }
1782
1783            // notify current top of stack it is losing focus
1784            if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) {
1785                try {
1786                    mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange(
1787                            (durationHint == AudioManager.AUDIOFOCUS_GAIN) ?
1788                                    AudioManager.AUDIOFOCUS_LOSS :
1789                                        AudioManager.AUDIOFOCUS_LOSS_TRANSIENT,
1790                            mFocusStack.peek().mClientId);
1791                } catch (RemoteException e) {
1792                    Log.e(TAG, " Failure to signal loss of focus due to "+ e);
1793                    e.printStackTrace();
1794                }
1795            }
1796
1797            // push focus requester at the top of the audio focus stack
1798            mFocusStack.push(new FocusStackEntry(mainStreamType, durationHint, false, fd, cb,
1799                    clientId));
1800        }//synchronized(mFocusStack)
1801
1802        // handle the potential premature death of the new holder of the focus
1803        // (premature death == death before abandoning focus)
1804        // Register for client death notification
1805        AudioFocusDeathHandler afdh = new AudioFocusDeathHandler(cb);
1806        try {
1807            cb.linkToDeath(afdh, 0);
1808        } catch (RemoteException e) {
1809            // client has already died!
1810            Log.w(TAG, " AudioFocus  requestAudioFocus() could not link to "+cb+" binder death");
1811        }
1812
1813        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
1814    }
1815
1816    /** @see AudioManager#abandonAudioFocus(IAudioFocusDispatcher) */
1817    public int abandonAudioFocus(IAudioFocusDispatcher fl, String clientId) {
1818        Log.i(TAG, " AudioFocus  abandonAudioFocus() from " + clientId);
1819
1820        // this will take care of notifying the new focus owner if needed
1821        removeFocusStackEntry(clientId, true);
1822
1823        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
1824    }
1825
1826
1827    public void unregisterAudioFocusClient(String clientId) {
1828        removeFocusStackEntry(clientId, false);
1829    }
1830
1831
1832    //==========================================================================================
1833    // RemoteControl
1834    //==========================================================================================
1835    /**
1836     * Receiver for media button intents. Handles the dispatching of the media button event
1837     * to one of the registered listeners, or if there was none, resumes the intent broadcast
1838     * to the rest of the system.
1839     */
1840    private class MediaButtonBroadcastReceiver extends BroadcastReceiver {
1841        @Override
1842        public void onReceive(Context context, Intent intent) {
1843            String action = intent.getAction();
1844            if (!Intent.ACTION_MEDIA_BUTTON.equals(action)) {
1845                return;
1846            }
1847            KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
1848            if (event != null) {
1849                // if in a call or ringing, do not break the current phone app behavior
1850                // TODO modify this to let the phone app specifically get the RC focus
1851                //      add modify the phone app to take advantage of the new API
1852                if ((getMode() == AudioSystem.MODE_IN_CALL) ||
1853                        (getMode() == AudioSystem.MODE_RINGTONE)) {
1854                    return;
1855                }
1856                synchronized(mRCStack) {
1857                    if (!mRCStack.empty()) {
1858                        // create a new intent specifically aimed at the current registered listener
1859                        Intent targetedIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
1860                        targetedIntent.putExtras(intent.getExtras());
1861                        targetedIntent.setComponent(mRCStack.peek().mReceiverComponent);
1862                        // trap the current broadcast
1863                        abortBroadcast();
1864                        //Log.v(TAG, " Sending intent" + targetedIntent);
1865                        context.sendBroadcast(targetedIntent, null);
1866                    }
1867                }
1868            }
1869        }
1870    }
1871
1872    private static class RemoteControlStackEntry {
1873        public ComponentName mReceiverComponent;// always non null
1874        // TODO implement registration expiration?
1875        //public int mRegistrationTime;
1876
1877        public RemoteControlStackEntry() {
1878        }
1879
1880        public RemoteControlStackEntry(ComponentName r) {
1881            mReceiverComponent = r;
1882        }
1883    }
1884
1885    private Stack<RemoteControlStackEntry> mRCStack = new Stack<RemoteControlStackEntry>();
1886
1887    /**
1888     * Helper function:
1889     * Display in the log the current entries in the remote control focus stack
1890     */
1891    private void dumpRCStack(PrintWriter pw) {
1892        pw.println("Remote Control stack entries:");
1893        synchronized(mRCStack) {
1894            Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
1895            while(stackIterator.hasNext()) {
1896                RemoteControlStackEntry fse = stackIterator.next();
1897                pw.println("     receiver:" + fse.mReceiverComponent);
1898            }
1899        }
1900    }
1901
1902    /**
1903     * Helper function:
1904     * Set the new remote control receiver at the top of the RC focus stack
1905     */
1906    private void pushMediaButtonReceiver(ComponentName newReceiver) {
1907        // already at top of stack?
1908        if (!mRCStack.empty() && mRCStack.peek().mReceiverComponent.equals(newReceiver)) {
1909            return;
1910        }
1911        Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
1912        while(stackIterator.hasNext()) {
1913            RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
1914            if(rcse.mReceiverComponent.equals(newReceiver)) {
1915                mRCStack.remove(rcse);
1916                break;
1917            }
1918        }
1919        mRCStack.push(new RemoteControlStackEntry(newReceiver));
1920    }
1921
1922    /**
1923     * Helper function:
1924     * Remove the remote control receiver from the RC focus stack
1925     */
1926    private void removeMediaButtonReceiver(ComponentName newReceiver) {
1927        Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
1928        while(stackIterator.hasNext()) {
1929            RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
1930            if(rcse.mReceiverComponent.equals(newReceiver)) {
1931                mRCStack.remove(rcse);
1932                break;
1933            }
1934        }
1935    }
1936
1937
1938    /** see AudioManager.registerMediaButtonEventReceiver(ComponentName eventReceiver) */
1939    public void registerMediaButtonEventReceiver(ComponentName eventReceiver) {
1940        Log.i(TAG, "  Remote Control   registerMediaButtonEventReceiver() for " + eventReceiver);
1941
1942        synchronized(mRCStack) {
1943            pushMediaButtonReceiver(eventReceiver);
1944        }
1945    }
1946
1947    /** see AudioManager.unregisterMediaButtonEventReceiver(ComponentName eventReceiver) */
1948    public void unregisterMediaButtonEventReceiver(ComponentName eventReceiver) {
1949        Log.i(TAG, "  Remote Control   registerMediaButtonEventReceiver() for " + eventReceiver);
1950
1951        synchronized(mRCStack) {
1952            removeMediaButtonReceiver(eventReceiver);
1953        }
1954    }
1955
1956
1957    @Override
1958    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1959        // TODO probably a lot more to do here than just the audio focus and remote control stacks
1960        dumpFocusStack(pw);
1961        dumpRCStack(pw);
1962    }
1963
1964
1965}
1966