1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
|
package com.android.onemedia.playback;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import android.content.Context;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import java.io.IOException;
import java.util.Map;
/**
* Helper class for wrapping a MediaPlayer and doing a lot of the default work
* to play audio. This class is not currently thread safe and all calls to it
* should be made on the same thread.
*/
public class LocalRenderer extends Renderer implements OnPreparedListener,
OnBufferingUpdateListener, OnCompletionListener, OnErrorListener,
OnAudioFocusChangeListener {
private static final String TAG = "MediaPlayerManager";
private static final boolean DEBUG = true;
private static long sDebugInstanceId = 0;
private static final String[] SUPPORTED_FEATURES = {
FEATURE_SET_CONTENT,
FEATURE_SET_NEXT_CONTENT,
FEATURE_PLAY,
FEATURE_PAUSE,
FEATURE_NEXT,
FEATURE_PREVIOUS,
FEATURE_SEEK_TO,
FEATURE_STOP
};
/**
* These are the states where it is valid to call play directly on the
* MediaPlayer.
*/
private static final int CAN_PLAY = STATE_READY | STATE_PAUSED | STATE_ENDED;
/**
* These are the states where we expect the MediaPlayer to be ready in the
* future, so we can set a flag to start playing when it is.
*/
private static final int CAN_READY_PLAY = STATE_INIT | STATE_PREPARING;
/**
* The states when it is valid to call pause on the MediaPlayer.
*/
private static final int CAN_PAUSE = STATE_PLAYING;
/**
* The states where it is valid to call seek on the MediaPlayer.
*/
private static final int CAN_SEEK = STATE_READY | STATE_PLAYING | STATE_PAUSED | STATE_ENDED;
/**
* The states where we expect the MediaPlayer to be ready in the future and
* can store a seek position to set later.
*/
private static final int CAN_READY_SEEK = STATE_INIT | STATE_PREPARING;
/**
* The states where it is valid to call stop on the MediaPlayer.
*/
private static final int CAN_STOP = STATE_READY | STATE_PLAYING | STATE_PAUSED | STATE_ENDED;
/**
* The states where it is valid to get the current play position and the
* duration from the MediaPlayer.
*/
private static final int CAN_GET_POSITION = STATE_READY | STATE_PLAYING | STATE_PAUSED;
private class PlayerContent {
public final String source;
public final Map<String, String> headers;
public PlayerContent(String source, Map<String, String> headers) {
this.source = source;
this.headers = headers;
}
}
private class AsyncErrorRetriever extends AsyncTask<HttpGet, Void, Void> {
private final long errorId;
private boolean closeHttpClient;
public AsyncErrorRetriever(long errorId) {
this.errorId = errorId;
closeHttpClient = false;
}
public boolean cancelRequestLocked(boolean closeHttp) {
closeHttpClient = closeHttp;
return this.cancel(false);
}
@Override
protected Void doInBackground(HttpGet[] params) {
synchronized (mErrorLock) {
if (isCancelled() || mHttpClient == null) {
if (mErrorRetriever == this) {
mErrorRetriever = null;
}
return null;
}
mSafeToCloseClient = false;
}
final PlaybackError error = new PlaybackError();
try {
HttpResponse response = mHttpClient.execute(params[0]);
synchronized (mErrorLock) {
if (mErrorId != errorId || mError == null) {
// A new error has occurred, abort
return null;
}
error.type = mError.type;
error.extra = mError.extra;
error.errorMessage = mError.errorMessage;
}
final int code = response.getStatusLine().getStatusCode();
if (code >= 300) {
error.extra = code;
}
final Bundle errorExtras = new Bundle();
Header[] headers = response.getAllHeaders();
if (headers != null && headers.length > 0) {
for (Header header : headers) {
errorExtras.putString(header.getName(), header.getValue());
}
error.errorExtras = errorExtras;
}
} catch (IOException e) {
Log.e(TAG, "IOException requesting from server, unable to get more exact error");
} finally {
synchronized (mErrorLock) {
mSafeToCloseClient = true;
if (mErrorRetriever == this) {
mErrorRetriever = null;
}
if (isCancelled()) {
if (closeHttpClient) {
mHttpClient.close();
mHttpClient = null;
}
return null;
}
}
}
mHandler.post(new Runnable() {
@Override
public void run() {
synchronized (mErrorLock) {
if (mErrorId == errorId) {
setError(error.type, error.extra, error.errorExtras, null);
}
}
}
});
return null;
}
}
private int mState = STATE_INIT;
private AudioManager mAudioManager;
private MediaPlayer mPlayer;
private PlayerContent mContent;
private MediaPlayer mNextPlayer;
private PlayerContent mNextContent;
private SurfaceHolder mHolder;
private SurfaceHolder.Callback mHolderCB;
private Context mContext;
private Handler mHandler = new Handler();
private AndroidHttpClient mHttpClient = AndroidHttpClient.newInstance("TUQ");
// The ongoing error request thread if there is one. This should only be
// modified while mErrorLock is held.
private AsyncErrorRetriever mErrorRetriever;
// This is set to false while a server request is being made to retrieve
// the current error. It should only be set while mErrorLock is held.
private boolean mSafeToCloseClient = true;
private final Object mErrorLock = new Object();
// A tracking id for the current error. This should only be modified while
// mErrorLock is held.
private long mErrorId = 0;
// The current error state of this player. This is cleared when the state
// leaves an error state and set when it enters one. This should only be
// modified when mErrorLock is held.
private PlaybackError mError;
private boolean mPlayOnReady;
private int mSeekOnReady;
private boolean mHasAudioFocus;
private long mDebugId = sDebugInstanceId++;
public LocalRenderer(Context context, Bundle params) {
super(context, params);
mContext = context;
mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
}
@Override
protected void initFeatures(Bundle params) {
for (String feature : SUPPORTED_FEATURES) {
mFeatures.add(feature);
}
}
/**
* Call this when completely finished with the MediaPlayerManager to have it
* clean up. The instance may not be used again after this is called.
*/
@Override
public void onDestroy() {
synchronized (mErrorLock) {
if (DEBUG) {
Log.d(TAG, "onDestroy, error retriever? " + mErrorRetriever + " safe to close? "
+ mSafeToCloseClient + " client? " + mHttpClient);
}
if (mErrorRetriever != null) {
mErrorRetriever.cancelRequestLocked(true);
mErrorRetriever = null;
}
// Increment the error id to ensure no errors are sent after this
// point.
mErrorId++;
if (mSafeToCloseClient) {
mHttpClient.close();
mHttpClient = null;
}
}
}
@Override
public void onPrepared(MediaPlayer player) {
if (!isCurrentPlayer(player)) {
return;
}
setState(STATE_READY);
if (DEBUG) {
Log.d(TAG, mDebugId + ": Finished preparing, seekOnReady is " + mSeekOnReady);
}
if (mSeekOnReady >= 0) {
onSeekTo(mSeekOnReady);
mSeekOnReady = -1;
}
if (mPlayOnReady) {
player.start();
setState(STATE_PLAYING);
}
}
@Override
public void onBufferingUpdate(MediaPlayer player, int percent) {
if (!isCurrentPlayer(player)) {
return;
}
pushOnBufferingUpdate(percent);
}
@Override
public void onCompletion(MediaPlayer player) {
if (!isCurrentPlayer(player)) {
return;
}
if (DEBUG) {
Log.d(TAG, mDebugId + ": Completed item. Have next item? " + (mNextPlayer != null));
}
if (mNextPlayer != null) {
if (mPlayer != null) {
mPlayer.release();
}
mPlayer = mNextPlayer;
mContent = mNextContent;
mNextPlayer = null;
mNextContent = null;
pushOnNextStarted();
return;
}
setState(STATE_ENDED);
}
@Override
public boolean onError(MediaPlayer player, int what, int extra) {
if (!isCurrentPlayer(player)) {
return false;
}
if (DEBUG) {
Log.d(TAG, mDebugId + ": Entered error state, what: " + what + " extra: " + extra);
}
synchronized (mErrorLock) {
++mErrorId;
mError = new PlaybackError();
mError.type = what;
mError.extra = extra;
}
if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN && extra == MediaPlayer.MEDIA_ERROR_IO
&& mContent != null && mContent.source.startsWith("http")) {
HttpGet request = new HttpGet(mContent.source);
if (mContent.headers != null) {
for (String key : mContent.headers.keySet()) {
request.addHeader(key, mContent.headers.get(key));
}
}
synchronized (mErrorLock) {
if (mErrorRetriever != null) {
mErrorRetriever.cancelRequestLocked(false);
}
mErrorRetriever = new AsyncErrorRetriever(mErrorId);
mErrorRetriever.execute(request);
}
} else {
setError(what, extra, null, null);
}
return true;
}
@Override
public void onAudioFocusChange(int focusChange) {
// TODO figure out appropriate logic for handling focus loss at the TUQ
// level.
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
if (mState == STATE_PLAYING) {
onPause();
mPlayOnReady = true;
}
mHasAudioFocus = false;
break;
case AudioManager.AUDIOFOCUS_LOSS:
if (mState == STATE_PLAYING) {
onPause();
mPlayOnReady = false;
}
pushOnFocusLost();
mHasAudioFocus = false;
break;
case AudioManager.AUDIOFOCUS_GAIN:
mHasAudioFocus = true;
if (mPlayOnReady) {
onPlay();
}
break;
default:
Log.d(TAG, "Unknown focus change event " + focusChange);
break;
}
}
@Override
public void setContent(Bundle request) {
setContent(request, null);
}
/**
* Prepares the player for the given playback request. If the holder is null
* it is assumed this is an audio only source. If playOnReady is set to true
* the media will begin playing as soon as it can.
*/
public void setContent(Bundle request, SurfaceHolder holder) {
String source = request.getString(RequestUtils.EXTRA_KEY_SOURCE);
Map<String, String> headers = null; // request.mHeaders;
boolean playOnReady = true; // request.mPlayOnReady;
if (DEBUG) {
Log.d(TAG, mDebugId + ": Settings new content. Have a player? " + (mPlayer != null)
+ " have a next player? " + (mNextPlayer != null));
}
cleanUpPlayer();
setState(STATE_PREPARING);
mPlayOnReady = playOnReady;
mSeekOnReady = -1;
final MediaPlayer newPlayer = new MediaPlayer();
requestAudioFocus();
mPlayer = newPlayer;
mContent = new PlayerContent(source, headers);
try {
if (headers != null) {
Uri sourceUri = Uri.parse(source);
newPlayer.setDataSource(mContext, sourceUri, headers);
} else {
newPlayer.setDataSource(source);
}
} catch (Exception e) {
setError(Listener.ERROR_LOAD_FAILED, 0, null, e);
return;
}
if (isHolderReady(holder, newPlayer)) {
preparePlayer(newPlayer, true);
}
}
@Override
public void setNextContent(Bundle request) {
String source = request.getString(RequestUtils.EXTRA_KEY_SOURCE);
Map<String, String> headers = null; // request.mHeaders;
// TODO support video
if (DEBUG) {
Log.d(TAG, mDebugId + ": Setting next content. Have player? " + (mPlayer != null)
+ " have next player? " + (mNextPlayer != null));
}
if (mPlayer == null) {
// The manager isn't being used to play anything, don't try to
// set a next.
return;
}
if (mNextPlayer != null) {
// Before setting up the new one clear out the old one and release
// it to ensure it doesn't play.
mPlayer.setNextMediaPlayer(null);
mNextPlayer.release();
mNextPlayer = null;
mNextContent = null;
}
if (source == null) {
// If there's no new content we're done
return;
}
final MediaPlayer newPlayer = new MediaPlayer();
try {
if (headers != null) {
Uri sourceUri = Uri.parse(source);
newPlayer.setDataSource(mContext, sourceUri, headers);
} else {
newPlayer.setDataSource(source);
}
} catch (Exception e) {
newPlayer.release();
// Don't return an error until we get to this item in playback
return;
}
if (preparePlayer(newPlayer, false)) {
mPlayer.setNextMediaPlayer(newPlayer);
mNextPlayer = newPlayer;
mNextContent = new PlayerContent(source, headers);
}
}
private void requestAudioFocus() {
int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
mHasAudioFocus = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
/**
* Start the player if possible or queue it to play when ready. If the
* player is in a state where it will never be ready returns false.
*
* @return true if the content was started or will be started later
*/
@Override
public boolean onPlay() {
MediaPlayer player = mPlayer;
if (player != null && mState == STATE_PLAYING) {
// already playing, just return
return true;
}
if (!mHasAudioFocus) {
requestAudioFocus();
}
if (player != null && canPlay()) {
player.start();
setState(STATE_PLAYING);
} else if (canReadyPlay()) {
mPlayOnReady = true;
} else if (!isPlaying()) {
return false;
}
return true;
}
/**
* Pause the player if possible or set it to not play when ready. If the
* player is in a state where it will never be ready returns false.
*
* @return true if the content was paused or will wait to play when ready
* later
*/
@Override
public boolean onPause() {
MediaPlayer player = mPlayer;
if (player != null && (mState & CAN_PAUSE) != 0) {
player.pause();
setState(STATE_PAUSED);
} else if ((mState & CAN_READY_PLAY) != 0) {
mPlayOnReady = false;
} else if (!isPaused()) {
return false;
}
return true;
}
/**
* Seek to a given position in the media. If the seek succeeded or will be
* performed when loading is complete returns true. If the position is not
* in range or the player will never be ready returns false.
*
* @param position The position to seek to in milliseconds
* @return true if playback was moved or will be moved when ready
*/
@Override
public boolean onSeekTo(int position) {
MediaPlayer player = mPlayer;
if (player != null && (mState & CAN_SEEK) != 0) {
if (position < 0 || position >= getDuration()) {
return false;
} else {
if (mState == STATE_ENDED) {
player.start();
player.pause();
setState(STATE_PAUSED);
}
player.seekTo(position);
}
} else if ((mState & CAN_READY_SEEK) != 0) {
mSeekOnReady = position;
} else {
return false;
}
return true;
}
/**
* Stop the player. It cannot be used again until
* {@link #setContent(String, boolean)} is called.
*
* @return true if stopping the player succeeded
*/
@Override
public boolean onStop() {
cleanUpPlayer();
setState(STATE_STOPPED);
return true;
}
public boolean isPlaying() {
return mState == STATE_PLAYING;
}
public boolean isPaused() {
return mState == STATE_PAUSED;
}
@Override
public long getSeekPosition() {
return ((mState & CAN_GET_POSITION) == 0) ? -1 : mPlayer.getCurrentPosition();
}
@Override
public long getDuration() {
return ((mState & CAN_GET_POSITION) == 0) ? -1 : mPlayer.getDuration();
}
private boolean canPlay() {
return ((mState & CAN_PLAY) != 0) && mHasAudioFocus;
}
private boolean canReadyPlay() {
return (mState & CAN_PLAY) != 0 || (mState & CAN_READY_PLAY) != 0;
}
/**
* Sends a state update if the listener exists
*/
private void setState(int state) {
if (state == mState) {
return;
}
Log.d(TAG, "Entering state " + state + " from state " + mState);
mState = state;
if (state != STATE_ERROR) {
// Don't notify error here, it'll get sent via onError
pushOnStateChanged(state);
}
}
private boolean preparePlayer(final MediaPlayer player, boolean current) {
player.setOnPreparedListener(this);
player.setOnBufferingUpdateListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
try {
player.prepareAsync();
if (current) {
setState(STATE_PREPARING);
}
} catch (IllegalStateException e) {
if (current) {
setError(Listener.ERROR_PREPARE_ERROR, 0, null, e);
}
return false;
}
return true;
}
/**
* @param extra
* @param e
*/
private void setError(int type, int extra, Bundle extras, Exception e) {
setState(STATE_ERROR);
pushOnError(type, extra, extras, e);
cleanUpPlayer();
return;
}
/**
* Checks if the holder is ready and either sets up a callback to wait for
* it or sets it directly. If
*
* @param holder
* @param player
* @return
*/
private boolean isHolderReady(final SurfaceHolder holder, final MediaPlayer player) {
mHolder = holder;
if (holder != null) {
if (holder.getSurface() != null && holder.getSurface().isValid()) {
player.setDisplay(holder);
return true;
} else {
Log.w(TAG, "Holder not null, waiting for it to be ready");
// If the holder isn't ready yet add a callback to set the
// holder when it's ready.
SurfaceHolder.Callback cb = new SurfaceHolder.Callback() {
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
@Override
public void surfaceCreated(SurfaceHolder arg0) {
if (player.equals(mPlayer)) {
player.setDisplay(arg0);
preparePlayer(player, true);
}
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
};
mHolderCB = cb;
holder.addCallback(cb);
return false;
}
}
return true;
}
private void cleanUpPlayer() {
if (DEBUG) {
Log.d(TAG, mDebugId + ": Cleaning up current player");
}
synchronized (mErrorLock) {
mError = null;
if (mErrorRetriever != null) {
mErrorRetriever.cancelRequestLocked(false);
// Don't set to null as we may need to cancel again with true if
// the object gets destroyed.
}
}
mAudioManager.abandonAudioFocus(this);
SurfaceHolder.Callback cb = mHolderCB;
mHolderCB = null;
SurfaceHolder holder = mHolder;
mHolder = null;
if (holder != null && cb != null) {
holder.removeCallback(cb);
}
MediaPlayer player = mPlayer;
mPlayer = null;
if (player != null) {
player.reset();
player.release();
}
}
private boolean isCurrentPlayer(MediaPlayer player) {
return player.equals(mPlayer);
}
}
|