Home | History | Annotate | Download | only in media
      1 /*
      2  * Copyright (C) 2008 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 
     17 package com.android.systemui.media;
     18 
     19 import android.content.Context;
     20 import android.media.AudioManager;
     21 import android.media.MediaPlayer;
     22 import android.media.MediaPlayer.OnCompletionListener;
     23 import android.net.Uri;
     24 import android.os.Looper;
     25 import android.os.PowerManager;
     26 import android.os.SystemClock;
     27 import android.util.Log;
     28 
     29 import java.util.LinkedList;
     30 
     31 /**
     32  * @hide
     33  * This class is provides the same interface and functionality as android.media.AsyncPlayer
     34  * with the following differences:
     35  * - whenever audio is played, audio focus is requested,
     36  * - whenever audio playback is stopped or the playback completed, audio focus is abandoned.
     37  */
     38 public class NotificationPlayer implements OnCompletionListener {
     39     private static final int PLAY = 1;
     40     private static final int STOP = 2;
     41     private static final boolean mDebug = false;
     42 
     43     private static final class Command {
     44         int code;
     45         Context context;
     46         Uri uri;
     47         boolean looping;
     48         int stream;
     49         long requestTime;
     50 
     51         public String toString() {
     52             return "{ code=" + code + " looping=" + looping + " stream=" + stream
     53                     + " uri=" + uri + " }";
     54         }
     55     }
     56 
     57     private LinkedList<Command> mCmdQueue = new LinkedList();
     58 
     59     private Looper mLooper;
     60 
     61     /*
     62      * Besides the use of audio focus, the only implementation difference between AsyncPlayer and
     63      * NotificationPlayer resides in the creation of the MediaPlayer. For the completion callback,
     64      * OnCompletionListener, to be called at the end of the playback, the MediaPlayer needs to
     65      * be created with a looper running so its event handler is not null.
     66      */
     67     private final class CreationAndCompletionThread extends Thread {
     68         public Command mCmd;
     69         public CreationAndCompletionThread(Command cmd) {
     70             super();
     71             mCmd = cmd;
     72         }
     73 
     74         public void run() {
     75             Looper.prepare();
     76             mLooper = Looper.myLooper();
     77             synchronized(this) {
     78                 AudioManager audioManager =
     79                     (AudioManager) mCmd.context.getSystemService(Context.AUDIO_SERVICE);
     80                 try {
     81                     MediaPlayer player = new MediaPlayer();
     82                     player.setAudioStreamType(mCmd.stream);
     83                     player.setDataSource(mCmd.context, mCmd.uri);
     84                     player.setLooping(mCmd.looping);
     85                     player.prepare();
     86                     if ((mCmd.uri != null) && (mCmd.uri.getEncodedPath() != null)
     87                             && (mCmd.uri.getEncodedPath().length() > 0)) {
     88                         if (!audioManager.isMusicActiveRemotely()) {
     89                             synchronized(mQueueAudioFocusLock) {
     90                                 if (mAudioManagerWithAudioFocus == null) {
     91                                     if (mDebug) Log.d(mTag, "requesting AudioFocus");
     92                                     if (mCmd.looping) {
     93                                         audioManager.requestAudioFocus(null, mCmd.stream,
     94                                                 AudioManager.AUDIOFOCUS_GAIN);
     95                                     } else {
     96                                         audioManager.requestAudioFocus(null, mCmd.stream,
     97                                                 AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
     98                                     }
     99                                     mAudioManagerWithAudioFocus = audioManager;
    100                                 } else {
    101                                     if (mDebug) Log.d(mTag, "AudioFocus was previously requested");
    102                                 }
    103                             }
    104                         }
    105                     }
    106                     // FIXME Having to start a new thread so we can receive completion callbacks
    107                     //  is wrong, as we kill this thread whenever a new sound is to be played. This
    108                     //  can lead to AudioFocus being released too early, before the second sound is
    109                     //  done playing. This class should be modified to use a single thread, on which
    110                     //  command are issued, and on which it receives the completion callbacks.
    111                     player.setOnCompletionListener(NotificationPlayer.this);
    112                     player.start();
    113                     if (mPlayer != null) {
    114                         mPlayer.release();
    115                     }
    116                     mPlayer = player;
    117                 }
    118                 catch (Exception e) {
    119                     Log.w(mTag, "error loading sound for " + mCmd.uri, e);
    120                 }
    121                 this.notify();
    122             }
    123             Looper.loop();
    124         }
    125     };
    126 
    127     private void startSound(Command cmd) {
    128         // Preparing can be slow, so if there is something else
    129         // is playing, let it continue until we're done, so there
    130         // is less of a glitch.
    131         try {
    132             if (mDebug) Log.d(mTag, "Starting playback");
    133             //-----------------------------------
    134             // This is were we deviate from the AsyncPlayer implementation and create the
    135             // MediaPlayer in a new thread with which we're synchronized
    136             synchronized(mCompletionHandlingLock) {
    137                 // if another sound was already playing, it doesn't matter we won't get notified
    138                 // of the completion, since only the completion notification of the last sound
    139                 // matters
    140                 if((mLooper != null)
    141                         && (mLooper.getThread().getState() != Thread.State.TERMINATED)) {
    142                     mLooper.quit();
    143                 }
    144                 mCompletionThread = new CreationAndCompletionThread(cmd);
    145                 synchronized(mCompletionThread) {
    146                     mCompletionThread.start();
    147                     mCompletionThread.wait();
    148                 }
    149             }
    150             //-----------------------------------
    151 
    152             long delay = SystemClock.uptimeMillis() - cmd.requestTime;
    153             if (delay > 1000) {
    154                 Log.w(mTag, "Notification sound delayed by " + delay + "msecs");
    155             }
    156         }
    157         catch (Exception e) {
    158             Log.w(mTag, "error loading sound for " + cmd.uri, e);
    159         }
    160     }
    161 
    162     private final class CmdThread extends java.lang.Thread {
    163         CmdThread() {
    164             super("NotificationPlayer-" + mTag);
    165         }
    166 
    167         public void run() {
    168             while (true) {
    169                 Command cmd = null;
    170 
    171                 synchronized (mCmdQueue) {
    172                     if (mDebug) Log.d(mTag, "RemoveFirst");
    173                     cmd = mCmdQueue.removeFirst();
    174                 }
    175 
    176                 switch (cmd.code) {
    177                 case PLAY:
    178                     if (mDebug) Log.d(mTag, "PLAY");
    179                     startSound(cmd);
    180                     break;
    181                 case STOP:
    182                     if (mDebug) Log.d(mTag, "STOP");
    183                     if (mPlayer != null) {
    184                         long delay = SystemClock.uptimeMillis() - cmd.requestTime;
    185                         if (delay > 1000) {
    186                             Log.w(mTag, "Notification stop delayed by " + delay + "msecs");
    187                         }
    188                         mPlayer.stop();
    189                         mPlayer.release();
    190                         mPlayer = null;
    191                         synchronized(mQueueAudioFocusLock) {
    192                             if (mAudioManagerWithAudioFocus != null) {
    193                                 mAudioManagerWithAudioFocus.abandonAudioFocus(null);
    194                                 mAudioManagerWithAudioFocus = null;
    195                             }
    196                         }
    197                         if((mLooper != null)
    198                                 && (mLooper.getThread().getState() != Thread.State.TERMINATED)) {
    199                             mLooper.quit();
    200                         }
    201                     } else {
    202                         Log.w(mTag, "STOP command without a player");
    203                     }
    204                     break;
    205                 }
    206 
    207                 synchronized (mCmdQueue) {
    208                     if (mCmdQueue.size() == 0) {
    209                         // nothing left to do, quit
    210                         // doing this check after we're done prevents the case where they
    211                         // added it during the operation from spawning two threads and
    212                         // trying to do them in parallel.
    213                         mThread = null;
    214                         releaseWakeLock();
    215                         return;
    216                     }
    217                 }
    218             }
    219         }
    220     }
    221 
    222     public void onCompletion(MediaPlayer mp) {
    223         synchronized(mQueueAudioFocusLock) {
    224             if (mAudioManagerWithAudioFocus != null) {
    225                 if (mDebug) Log.d(mTag, "onCompletion() abandonning AudioFocus");
    226                 mAudioManagerWithAudioFocus.abandonAudioFocus(null);
    227                 mAudioManagerWithAudioFocus = null;
    228             } else {
    229                 if (mDebug) Log.d(mTag, "onCompletion() no need to abandon AudioFocus");
    230             }
    231         }
    232         // if there are no more sounds to play, end the Looper to listen for media completion
    233         synchronized (mCmdQueue) {
    234             if (mCmdQueue.size() == 0) {
    235                 synchronized(mCompletionHandlingLock) {
    236                     if(mLooper != null) {
    237                         mLooper.quit();
    238                     }
    239                     mCompletionThread = null;
    240                 }
    241             }
    242         }
    243     }
    244 
    245     private String mTag;
    246     private CmdThread mThread;
    247     private CreationAndCompletionThread mCompletionThread;
    248     private final Object mCompletionHandlingLock = new Object();
    249     private MediaPlayer mPlayer;
    250     private PowerManager.WakeLock mWakeLock;
    251     private final Object mQueueAudioFocusLock = new Object();
    252     private AudioManager mAudioManagerWithAudioFocus; // synchronized on mQueueAudioFocusLock
    253 
    254     // The current state according to the caller.  Reality lags behind
    255     // because of the asynchronous nature of this class.
    256     private int mState = STOP;
    257 
    258     /**
    259      * Construct a NotificationPlayer object.
    260      *
    261      * @param tag a string to use for debugging
    262      */
    263     public NotificationPlayer(String tag) {
    264         if (tag != null) {
    265             mTag = tag;
    266         } else {
    267             mTag = "NotificationPlayer";
    268         }
    269     }
    270 
    271     /**
    272      * Start playing the sound.  It will actually start playing at some
    273      * point in the future.  There are no guarantees about latency here.
    274      * Calling this before another audio file is done playing will stop
    275      * that one and start the new one.
    276      *
    277      * @param context Your application's context.
    278      * @param uri The URI to play.  (see {@link MediaPlayer#setDataSource(Context, Uri)})
    279      * @param looping Whether the audio should loop forever.
    280      *          (see {@link MediaPlayer#setLooping(boolean)})
    281      * @param stream the AudioStream to use.
    282      *          (see {@link MediaPlayer#setAudioStreamType(int)})
    283      */
    284     public void play(Context context, Uri uri, boolean looping, int stream) {
    285         Command cmd = new Command();
    286         cmd.requestTime = SystemClock.uptimeMillis();
    287         cmd.code = PLAY;
    288         cmd.context = context;
    289         cmd.uri = uri;
    290         cmd.looping = looping;
    291         cmd.stream = stream;
    292         synchronized (mCmdQueue) {
    293             enqueueLocked(cmd);
    294             mState = PLAY;
    295         }
    296     }
    297 
    298     /**
    299      * Stop a previously played sound.  It can't be played again or unpaused
    300      * at this point.  Calling this multiple times has no ill effects.
    301      */
    302     public void stop() {
    303         synchronized (mCmdQueue) {
    304             // This check allows stop to be called multiple times without starting
    305             // a thread that ends up doing nothing.
    306             if (mState != STOP) {
    307                 Command cmd = new Command();
    308                 cmd.requestTime = SystemClock.uptimeMillis();
    309                 cmd.code = STOP;
    310                 enqueueLocked(cmd);
    311                 mState = STOP;
    312             }
    313         }
    314     }
    315 
    316     private void enqueueLocked(Command cmd) {
    317         mCmdQueue.add(cmd);
    318         if (mThread == null) {
    319             acquireWakeLock();
    320             mThread = new CmdThread();
    321             mThread.start();
    322         }
    323     }
    324 
    325     /**
    326      * We want to hold a wake lock while we do the prepare and play.  The stop probably is
    327      * optional, but it won't hurt to have it too.  The problem is that if you start a sound
    328      * while you're holding a wake lock (e.g. an alarm starting a notification), you want the
    329      * sound to play, but if the CPU turns off before mThread gets to work, it won't.  The
    330      * simplest way to deal with this is to make it so there is a wake lock held while the
    331      * thread is starting or running.  You're going to need the WAKE_LOCK permission if you're
    332      * going to call this.
    333      *
    334      * This must be called before the first time play is called.
    335      *
    336      * @hide
    337      */
    338     public void setUsesWakeLock(Context context) {
    339         if (mWakeLock != null || mThread != null) {
    340             // if either of these has happened, we've already played something.
    341             // and our releases will be out of sync.
    342             throw new RuntimeException("assertion failed mWakeLock=" + mWakeLock
    343                     + " mThread=" + mThread);
    344         }
    345         PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
    346         mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, mTag);
    347     }
    348 
    349     private void acquireWakeLock() {
    350         if (mWakeLock != null) {
    351             mWakeLock.acquire();
    352         }
    353     }
    354 
    355     private void releaseWakeLock() {
    356         if (mWakeLock != null) {
    357             mWakeLock.release();
    358         }
    359     }
    360 }
    361