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