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