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