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