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