forked from hitherejoe/Vineyard
-
Notifications
You must be signed in to change notification settings - Fork 6
/
PlaybackActivity.java
428 lines (370 loc) · 15.2 KB
/
PlaybackActivity.java
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
package com.hitherejoe.vineyard.ui.activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadata;
import android.media.MediaPlayer;
import android.media.session.MediaController;
import android.media.session.MediaSession;
import android.media.session.PlaybackState;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.View;
import android.widget.VideoView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.hitherejoe.vineyard.R;
import com.hitherejoe.vineyard.data.DataManager;
import com.hitherejoe.vineyard.data.model.Post;
import com.hitherejoe.vineyard.ui.fragment.PlaybackOverlayFragment;
import com.hitherejoe.vineyard.util.NetworkUtil;
import com.hitherejoe.vineyard.util.ToastFactory;
import java.util.ArrayList;
import javax.inject.Inject;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* PlaybackActivity for video playback that loads PlaybackOverlayFragment and handles
* the MediaSession object used to maintain the state of the media playback.
*/
public class PlaybackActivity extends BaseActivity {
public static final String AUTO_PLAY = "auto_play";
public static final String POST = "post";
public static final String POST_LIST = "postList";
public static final String EXTRA_IS_LOOP_ENABLED = "EXTRA_IS_LOOP_ENABLED";
private boolean mWasSkipPressed;
private boolean mIsAutoLoopEnabled;
@Inject DataManager mDataManager;
@Bind(R.id.videoView)
VideoView mVideoView;
@Bind(R.id.layout_loading_overlay)
View mLoadingOverlay;
public enum LeanbackPlaybackState {
PLAYING, PAUSED, IDLE
}
private ArrayList<Post> mPostsList;
private LeanbackPlaybackState mPlaybackState;
private MediaPlayer mMediaPlayer;
private MediaSession mSession;
private Post mCurrentPost;
private int mPosition;
private int mCurrentItem;
private long mStartTimeMillis;
private long mDuration;
public static Intent newStartIntent(Context context, Post post, ArrayList<Post> postList) {
Intent intent = new Intent(context, PlaybackActivity.class);
intent.putExtra(POST, post);
intent.putParcelableArrayListExtra(POST_LIST, postList);
return intent;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPlaybackState = LeanbackPlaybackState.IDLE;
mPosition = 0;
mDuration = -1;
mWasSkipPressed = false;
createMediaSession();
setContentView(R.layout.activity_playback);
ButterKnife.bind(this);
getActivityComponent().inject(this);
mIsAutoLoopEnabled = mDataManager.getPreferencesHelper().getShouldAutoLoop();
mCurrentPost = getIntent().getParcelableExtra(PlaybackActivity.POST);
if (mCurrentPost == null) {
throw new IllegalArgumentException("PlaybackActivity requires a Post object!");
}
mPostsList = getIntent().getExtras().getParcelableArrayList(POST_LIST);
if (mPostsList != null) {
for (int i = 0; i < mPostsList.size(); i++) {
if (mCurrentPost.equals(mPostsList.get(i))) mCurrentItem = i;
}
}
loadViews();
playPause(true);
}
@Override
public void onPause() {
super.onPause();
if (mVideoView.isPlaying()) {
if (!requestVisibleBehind(true)) {
// Try to play behind launcher, but if it fails, stop playback.
playPause(false);
}
} else {
requestVisibleBehind(false);
}
}
@Override
protected void onStop() {
super.onStop();
playPause(false);
}
@Override
public void onDestroy() {
super.onDestroy();
stopPlayback();
mMediaPlayer.release();
mVideoView.suspend();
mVideoView.setVideoURI(null);
mSession.release();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BUTTON_R1) {
mWasSkipPressed = true;
getMediaController().getTransportControls().skipToNext();
return true;
} else if (keyCode == KeyEvent.KEYCODE_BUTTON_L1) {
mWasSkipPressed = true;
getMediaController().getTransportControls().skipToPrevious();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onVisibleBehindCanceled() {
playPause(false);
super.onVisibleBehindCanceled();
}
@Override
public boolean onSearchRequested() {
return true;
}
private void loadViews() {
mVideoView.setFocusable(false);
mVideoView.setFocusableInTouchMode(false);
setVideoPath(mCurrentPost.videoUrl);
}
private void setPosition(int position) {
if (position > mDuration) {
mPosition = (int) mDuration;
} else if (position < 0) {
mPosition = 0;
} else {
mPosition = position;
}
mStartTimeMillis = System.currentTimeMillis();
}
private void createMediaSession() {
if (mSession == null) {
mSession = new MediaSession(this, getString(R.string.app_name));
mSession.setCallback(new MediaSessionCallback());
mSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
mSession.setActive(true);
setMediaController(new MediaController(this, mSession.getSessionToken()));
}
}
private void playPause(boolean doPlay) {
if (mPlaybackState == LeanbackPlaybackState.IDLE) setupCallbacks();
if (doPlay && mPlaybackState != LeanbackPlaybackState.PLAYING) {
mPlaybackState = LeanbackPlaybackState.PLAYING;
if (mPosition > 0) {
mVideoView.seekTo(mPosition);
}
mVideoView.start();
mStartTimeMillis = System.currentTimeMillis();
} else {
mPosition = mVideoView.getCurrentPosition();
mPlaybackState = LeanbackPlaybackState.PAUSED;
int timeElapsedSinceStart = (int) (System.currentTimeMillis() - mStartTimeMillis);
setPosition(mPosition + timeElapsedSinceStart);
mVideoView.pause();
}
updatePlaybackState();
}
private void updatePlaybackState() {
PlaybackState.Builder stateBuilder =
new PlaybackState.Builder().setActions(getAvailableActions());
int state = PlaybackState.STATE_PLAYING;
if (mPlaybackState == LeanbackPlaybackState.PAUSED
|| mPlaybackState == LeanbackPlaybackState.IDLE) {
state = PlaybackState.STATE_PAUSED;
}
stateBuilder.setState(state, mPosition, 1.0f);
mSession.setPlaybackState(stateBuilder.build());
}
private long getAvailableActions() {
long actions = PlaybackState.ACTION_PLAY |
PlaybackState.ACTION_PLAY_FROM_MEDIA_ID |
PlaybackState.ACTION_PLAY_FROM_SEARCH |
PlaybackState.ACTION_SKIP_TO_NEXT |
PlaybackState.ACTION_SKIP_TO_PREVIOUS |
PlaybackState.ACTION_FAST_FORWARD |
PlaybackState.ACTION_REWIND;
if (mPlaybackState == LeanbackPlaybackState.PLAYING) actions |= PlaybackState.ACTION_PAUSE;
return actions;
}
private void updateMetadata(Post post) {
final MediaMetadata.Builder metadataBuilder = new MediaMetadata.Builder();
String title = post.description.replace("_", " -");
metadataBuilder.putString(MediaMetadata.METADATA_KEY_MEDIA_ID, post.postId);
metadataBuilder.putString(MediaMetadata.METADATA_KEY_DISPLAY_TITLE, title);
metadataBuilder.putString(MediaMetadata.METADATA_KEY_DISPLAY_SUBTITLE,
post.username);
metadataBuilder.putString(MediaMetadata.METADATA_KEY_DISPLAY_DESCRIPTION,
post.description);
metadataBuilder.putString(MediaMetadata.METADATA_KEY_DISPLAY_ICON_URI,
post.avatarUrl);
metadataBuilder.putLong(MediaMetadata.METADATA_KEY_DURATION, mVideoView.getDuration());
// And at minimum the title and artist for legacy support
metadataBuilder.putString(MediaMetadata.METADATA_KEY_TITLE, title);
metadataBuilder.putString(MediaMetadata.METADATA_KEY_ARTIST, post.username);
Glide.with(this)
.load(post.avatarUrl)
.asBitmap()
.into(new SimpleTarget<Bitmap>(500, 500) {
@Override
public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
metadataBuilder.putBitmap(MediaMetadata.METADATA_KEY_ART, bitmap);
mSession.setMetadata(metadataBuilder.build());
}
});
}
private void setupCallbacks() {
mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mVideoView.stopPlayback();
mPlaybackState = LeanbackPlaybackState.IDLE;
return false;
}
});
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mMediaPlayer = mp;
mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
if (percent > 40) {
updatePlaybackState();
mLoadingOverlay.setVisibility(View.GONE);
}
}
});
updateMetadata(mCurrentPost);
}
});
mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
if (!mIsAutoLoopEnabled) {
mPlaybackState = LeanbackPlaybackState.IDLE;
} else {
//TODO: It'd be better to use the MediaPlayer looping functionality, but
// this broke the seek bar progress due to the gap between loops...
mMediaPlayer.start();
PlaybackState.Builder stateBuilder =
new PlaybackState.Builder().setActions(getAvailableActions());
stateBuilder.setState(PlaybackOverlayFragment.STATE_LOOPING, 0, 1.0f);
mSession.setPlaybackState(stateBuilder.build());
}
}
});
}
private void stopPlayback() {
if (mVideoView != null) mVideoView.stopPlayback();
}
private class MediaSessionCallback extends MediaSession.Callback {
@Override
public void onPlay() {
playPause(true);
}
@Override
public void onPause() {
playPause(false);
}
@Override
public void onPlayFromMediaId(String mediaId, Bundle extras) {
if (mWasSkipPressed || !mIsAutoLoopEnabled) {
if (NetworkUtil.isNetworkConnected(PlaybackActivity.this)) {
for (Post post : mPostsList) {
if (post.postId.equals(mediaId)) {
mCurrentPost = post;
setVideoPath(mCurrentPost.videoUrl);
mPlaybackState = LeanbackPlaybackState.PAUSED;
playPause(extras.getBoolean(AUTO_PLAY));
}
}
mWasSkipPressed = false;
} else {
ToastFactory.createWifiErrorToast(PlaybackActivity.this).show();
finish();
}
}
}
@Override
public void onSkipToNext() {
if (mWasSkipPressed || !mIsAutoLoopEnabled) {
PlaybackState.Builder stateBuilder =
new PlaybackState.Builder().setActions(getAvailableActions());
stateBuilder.setState(PlaybackState.STATE_SKIPPING_TO_NEXT, 0, 1.0f);
mSession.setPlaybackState(stateBuilder.build());
mCurrentItem++;
if (mCurrentItem == mPostsList.size()) {
mCurrentItem = 0;
}
Bundle bundle = new Bundle(1);
bundle.putBoolean(PlaybackActivity.AUTO_PLAY, true);
String nextId = mPostsList.get(mCurrentItem).postId;
getMediaController().getTransportControls().playFromMediaId(nextId, bundle);
}
}
@Override
public void onSkipToPrevious() {
if (mWasSkipPressed || !mIsAutoLoopEnabled) {
PlaybackState.Builder stateBuilder =
new PlaybackState.Builder().setActions(getAvailableActions());
stateBuilder.setState(PlaybackState.STATE_SKIPPING_TO_PREVIOUS, 0, 1.0f);
mSession.setPlaybackState(stateBuilder.build());
if (mCurrentItem-- < 0) mCurrentItem = mPostsList.size() - 1;
Bundle bundle = new Bundle(1);
bundle.putBoolean(PlaybackActivity.AUTO_PLAY, true);
String prevId = mPostsList.get(mCurrentItem).postId;
getMediaController().getTransportControls().playFromMediaId(prevId, bundle);
}
}
@Override
public void onSeekTo(long pos) {
setPosition((int) pos);
mVideoView.seekTo(mPosition);
updatePlaybackState();
}
@Override
public void onFastForward() {
if (mDuration != -1) {
// Fast forward 2 seconds.
setPosition(mVideoView.getCurrentPosition() + (2 * 1000));
mVideoView.seekTo(mPosition);
updatePlaybackState();
}
}
@Override
public void onRewind() {
// rewind 2 seconds
setPosition(mVideoView.getCurrentPosition() - (2 * 1000));
mVideoView.seekTo(mPosition);
updatePlaybackState();
}
@Override
public void onCustomAction(@NonNull String action, Bundle extras) {
if (action.equals(PlaybackOverlayFragment.CUSTOM_ACTION_LOOP)) {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mIsAutoLoopEnabled = extras.getBoolean(EXTRA_IS_LOOP_ENABLED);
}
} else if (action.equals(PlaybackOverlayFragment.CUSTOM_ACTION_SKIP_VIDEO)) {
mWasSkipPressed = true;
}
super.onCustomAction(action, extras);
}
}
private void setVideoPath(String videoUrl) {
mLoadingOverlay.setVisibility(View.VISIBLE);
setPosition(0);
mVideoView.setVideoPath(videoUrl);
mStartTimeMillis = 0;
}
}