-
Notifications
You must be signed in to change notification settings - Fork 6k
/
SessionPlayerConnector.java
761 lines (679 loc) · 25.5 KB
/
SessionPlayerConnector.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
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.ext.media2;
import static com.google.android.exoplayer2.util.Util.postOrRun;
import android.os.Handler;
import androidx.annotation.FloatRange;
import androidx.annotation.GuardedBy;
import androidx.annotation.IntRange;
import androidx.annotation.Nullable;
import androidx.core.util.ObjectsCompat;
import androidx.core.util.Pair;
import androidx.media.AudioAttributesCompat;
import androidx.media2.common.CallbackMediaItem;
import androidx.media2.common.FileMediaItem;
import androidx.media2.common.MediaItem;
import androidx.media2.common.MediaMetadata;
import androidx.media2.common.SessionPlayer;
import com.google.android.exoplayer2.ControlDispatcher;
import com.google.android.exoplayer2.DefaultControlDispatcher;
import com.google.android.exoplayer2.ExoPlayerLibraryInfo;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Log;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import org.checkerframework.checker.nullness.compatqual.NullableType;
/**
* An implementation of {@link SessionPlayer} that wraps a given ExoPlayer {@link Player} instance.
*
* <p>Internally this implementation posts operations to and receives callbacks on the thread
* associated with {@link Player#getApplicationLooper()}, so it is important not to block this
* thread. In particular, when awaiting the result of an asynchronous session player operation, apps
* should generally use {@link ListenableFuture#addListener(Runnable, Executor)} to be notified of
* completion, rather than calling the blocking {@link ListenableFuture#get()} method.
*/
public final class SessionPlayerConnector extends SessionPlayer {
static {
ExoPlayerLibraryInfo.registerModule("goog.exo.media2");
}
private static final String TAG = "SessionPlayerConnector";
private static final boolean DEBUG = false;
private static final int END_OF_PLAYLIST = -1;
private final Object stateLock = new Object();
private final Handler taskHandler;
private final Executor taskHandlerExecutor;
private final PlayerWrapper player;
private final PlayerCommandQueue playerCommandQueue;
@GuardedBy("stateLock")
private final Map<MediaItem, Integer> mediaItemToBuffState = new HashMap<>();
@GuardedBy("stateLock")
/* @PlayerState */
private int state;
@GuardedBy("stateLock")
private boolean closed;
// Should be only accessed on the executor, which is currently single-threaded.
@Nullable private MediaItem currentMediaItem;
/**
* Creates an instance using {@link DefaultMediaItemConverter} to convert between ExoPlayer and
* media2 MediaItems and {@link DefaultControlDispatcher} to dispatch player commands.
*
* @param player The player to wrap.
*/
public SessionPlayerConnector(Player player) {
this(player, new DefaultMediaItemConverter());
}
/**
* Creates an instance using the provided {@link ControlDispatcher} to dispatch player commands.
*
* @param player The player to wrap.
* @param mediaItemConverter The {@link MediaItemConverter}.
*/
public SessionPlayerConnector(Player player, MediaItemConverter mediaItemConverter) {
Assertions.checkNotNull(player);
Assertions.checkNotNull(mediaItemConverter);
state = PLAYER_STATE_IDLE;
taskHandler = new Handler(player.getApplicationLooper());
taskHandlerExecutor = (runnable) -> postOrRun(taskHandler, runnable);
this.player = new PlayerWrapper(new ExoPlayerWrapperListener(), player, mediaItemConverter);
playerCommandQueue = new PlayerCommandQueue(this.player, taskHandler);
}
/**
* Sets the {@link ControlDispatcher}.
*
* @param controlDispatcher The {@link ControlDispatcher}.
*/
public void setControlDispatcher(ControlDispatcher controlDispatcher) {
player.setControlDispatcher(controlDispatcher);
}
@Override
public ListenableFuture<PlayerResult> play() {
return playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_PLAY, /* command= */ player::play);
}
@Override
public ListenableFuture<PlayerResult> pause() {
return playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_PAUSE, /* command= */ player::pause);
}
@Override
public ListenableFuture<PlayerResult> prepare() {
return playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_PREPARE, /* command= */ player::prepare);
}
@Override
public ListenableFuture<PlayerResult> seekTo(long position) {
return playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_SEEK_TO,
/* command= */ () -> player.seekTo(position),
/* tag= */ position);
}
@Override
public ListenableFuture<PlayerResult> setPlaybackSpeed(
@FloatRange(from = 0.0f, to = Float.MAX_VALUE, fromInclusive = false) float playbackSpeed) {
Assertions.checkArgument(playbackSpeed > 0f);
return playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_SET_SPEED,
/* command= */ () -> {
player.setPlaybackSpeed(playbackSpeed);
return true;
});
}
@Override
public ListenableFuture<PlayerResult> setAudioAttributes(AudioAttributesCompat attr) {
return playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_SET_AUDIO_ATTRIBUTES,
/* command= */ () -> {
player.setAudioAttributes(Assertions.checkNotNull(attr));
return true;
});
}
@Override
/* @PlayerState */
public int getPlayerState() {
synchronized (stateLock) {
return state;
}
}
@Override
public long getCurrentPosition() {
long position =
runPlayerCallableBlocking(
/* callable= */ player::getCurrentPosition,
/* defaultValueWhenException= */ UNKNOWN_TIME);
return position >= 0 ? position : UNKNOWN_TIME;
}
@Override
public long getDuration() {
long position =
runPlayerCallableBlocking(
/* callable= */ player::getDuration, /* defaultValueWhenException= */ UNKNOWN_TIME);
return position >= 0 ? position : UNKNOWN_TIME;
}
@Override
public long getBufferedPosition() {
long position =
runPlayerCallableBlocking(
/* callable= */ player::getBufferedPosition,
/* defaultValueWhenException= */ UNKNOWN_TIME);
return position >= 0 ? position : UNKNOWN_TIME;
}
@Override
/* @BuffState */
public int getBufferingState() {
@Nullable
MediaItem mediaItem =
this.<@NullableType MediaItem>runPlayerCallableBlocking(
/* callable= */ player::getCurrentMediaItem, /* defaultValueWhenException= */ null);
if (mediaItem == null) {
return BUFFERING_STATE_UNKNOWN;
}
@Nullable Integer buffState;
synchronized (stateLock) {
buffState = mediaItemToBuffState.get(mediaItem);
}
return buffState == null ? BUFFERING_STATE_UNKNOWN : buffState;
}
@Override
@FloatRange(from = 0.0f, to = Float.MAX_VALUE, fromInclusive = false)
public float getPlaybackSpeed() {
return runPlayerCallableBlocking(
/* callable= */ player::getPlaybackSpeed, /* defaultValueWhenException= */ 1.0f);
}
@Override
@Nullable
public AudioAttributesCompat getAudioAttributes() {
return runPlayerCallableBlockingWithNullOnException(/* callable= */ player::getAudioAttributes);
}
/**
* {@inheritDoc}
*
* <p>{@link FileMediaItem} and {@link CallbackMediaItem} are not supported.
*/
@Override
public ListenableFuture<PlayerResult> setMediaItem(MediaItem item) {
Assertions.checkNotNull(item);
Assertions.checkArgument(!(item instanceof FileMediaItem));
Assertions.checkArgument(!(item instanceof CallbackMediaItem));
ListenableFuture<PlayerResult> result =
playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_SET_MEDIA_ITEM, () -> player.setMediaItem(item));
return result;
}
/**
* {@inheritDoc}
*
* <p>{@link FileMediaItem} and {@link CallbackMediaItem} are not supported.
*/
@Override
public ListenableFuture<PlayerResult> setPlaylist(
final List<MediaItem> playlist, @Nullable MediaMetadata metadata) {
Assertions.checkNotNull(playlist);
Assertions.checkArgument(!playlist.isEmpty());
for (int i = 0; i < playlist.size(); i++) {
MediaItem item = playlist.get(i);
Assertions.checkNotNull(item);
Assertions.checkArgument(!(item instanceof FileMediaItem));
Assertions.checkArgument(!(item instanceof CallbackMediaItem));
for (int j = 0; j < i; j++) {
Assertions.checkArgument(
item != playlist.get(j),
"playlist shouldn't contain duplicated item, index=" + i + " vs index=" + j);
}
}
ListenableFuture<PlayerResult> result =
playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_SET_PLAYLIST,
/* command= */ () -> player.setPlaylist(playlist, metadata));
return result;
}
/**
* {@inheritDoc}
*
* <p>{@link FileMediaItem} and {@link CallbackMediaItem} are not supported.
*/
@Override
public ListenableFuture<PlayerResult> addPlaylistItem(int index, MediaItem item) {
Assertions.checkArgument(index >= 0);
Assertions.checkNotNull(item);
Assertions.checkArgument(!(item instanceof FileMediaItem));
Assertions.checkArgument(!(item instanceof CallbackMediaItem));
ListenableFuture<PlayerResult> result =
playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_ADD_PLAYLIST_ITEM,
/* command= */ () -> player.addPlaylistItem(index, item));
return result;
}
@Override
public ListenableFuture<PlayerResult> removePlaylistItem(@IntRange(from = 0) int index) {
Assertions.checkArgument(index >= 0);
ListenableFuture<PlayerResult> result =
playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_REMOVE_PLAYLIST_ITEM,
/* command= */ () -> player.removePlaylistItem(index));
return result;
}
/**
* {@inheritDoc}
*
* <p>{@link FileMediaItem} and {@link CallbackMediaItem} are not supported.
*/
@Override
public ListenableFuture<PlayerResult> replacePlaylistItem(int index, MediaItem item) {
Assertions.checkArgument(index >= 0);
Assertions.checkNotNull(item);
Assertions.checkArgument(!(item instanceof FileMediaItem));
Assertions.checkArgument(!(item instanceof CallbackMediaItem));
ListenableFuture<PlayerResult> result =
playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_REPLACE_PLAYLIST_ITEM,
/* command= */ () -> player.replacePlaylistItem(index, item));
return result;
}
@Override
public ListenableFuture<PlayerResult> skipToPreviousPlaylistItem() {
ListenableFuture<PlayerResult> result =
playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_SKIP_TO_PREVIOUS_PLAYLIST_ITEM,
/* command= */ player::skipToPreviousPlaylistItem);
result.addListener(this::notifySkipToCompletedOnHandler, taskHandlerExecutor);
return result;
}
@Override
public ListenableFuture<PlayerResult> skipToNextPlaylistItem() {
ListenableFuture<PlayerResult> result =
playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_SKIP_TO_NEXT_PLAYLIST_ITEM,
/* command= */ player::skipToNextPlaylistItem);
result.addListener(this::notifySkipToCompletedOnHandler, taskHandlerExecutor);
return result;
}
@Override
public ListenableFuture<PlayerResult> skipToPlaylistItem(@IntRange(from = 0) int index) {
Assertions.checkArgument(index >= 0);
ListenableFuture<PlayerResult> result =
playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_SKIP_TO_PLAYLIST_ITEM,
/* command= */ () -> player.skipToPlaylistItem(index));
result.addListener(this::notifySkipToCompletedOnHandler, taskHandlerExecutor);
return result;
}
@Override
public ListenableFuture<PlayerResult> updatePlaylistMetadata(@Nullable MediaMetadata metadata) {
return playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_UPDATE_LIST_METADATA,
/* command= */ () -> {
boolean handled = player.updatePlaylistMetadata(metadata);
if (handled) {
notifySessionPlayerCallback(
callback ->
callback.onPlaylistMetadataChanged(SessionPlayerConnector.this, metadata));
}
return handled;
});
}
@Override
public ListenableFuture<PlayerResult> setRepeatMode(int repeatMode) {
return playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_SET_REPEAT_MODE,
/* command= */ () -> player.setRepeatMode(repeatMode));
}
@Override
public ListenableFuture<PlayerResult> setShuffleMode(int shuffleMode) {
return playerCommandQueue.addCommand(
PlayerCommandQueue.COMMAND_CODE_PLAYER_SET_SHUFFLE_MODE,
/* command= */ () -> player.setShuffleMode(shuffleMode));
}
@Override
@Nullable
public List<MediaItem> getPlaylist() {
return runPlayerCallableBlockingWithNullOnException(/* callable= */ player::getPlaylist);
}
@Override
@Nullable
public MediaMetadata getPlaylistMetadata() {
return runPlayerCallableBlockingWithNullOnException(
/* callable= */ player::getPlaylistMetadata);
}
@Override
public int getRepeatMode() {
return runPlayerCallableBlocking(
/* callable= */ player::getRepeatMode, /* defaultValueWhenException= */ REPEAT_MODE_NONE);
}
@Override
public int getShuffleMode() {
return runPlayerCallableBlocking(
/* callable= */ player::getShuffleMode, /* defaultValueWhenException= */ SHUFFLE_MODE_NONE);
}
@Override
@Nullable
public MediaItem getCurrentMediaItem() {
return runPlayerCallableBlockingWithNullOnException(
/* callable= */ player::getCurrentMediaItem);
}
@Override
public int getCurrentMediaItemIndex() {
return runPlayerCallableBlocking(
/* callable= */ player::getCurrentMediaItemIndex,
/* defaultValueWhenException= */ END_OF_PLAYLIST);
}
@Override
public int getPreviousMediaItemIndex() {
return runPlayerCallableBlocking(
/* callable= */ player::getPreviousMediaItemIndex,
/* defaultValueWhenException= */ END_OF_PLAYLIST);
}
@Override
public int getNextMediaItemIndex() {
return runPlayerCallableBlocking(
/* callable= */ player::getNextMediaItemIndex,
/* defaultValueWhenException= */ END_OF_PLAYLIST);
}
@Override
public void close() {
synchronized (stateLock) {
if (closed) {
return;
}
closed = true;
}
reset();
this.<Void>runPlayerCallableBlocking(
/* callable= */ () -> {
player.close();
return null;
});
super.close();
}
// SessionPlayerConnector-specific functions.
/**
* Returns whether the current media item is seekable.
*
* @return {@code true} if supported. {@code false} otherwise.
*/
/* package */ boolean isCurrentMediaItemSeekable() {
return runPlayerCallableBlocking(
/* callable= */ player::isCurrentMediaItemSeekable, /* defaultValueWhenException= */ false);
}
/**
* Returns whether {@link #skipToPlaylistItem(int)} is supported.
*
* @return {@code true} if supported. {@code false} otherwise.
*/
/* package */ boolean canSkipToPlaylistItem() {
return runPlayerCallableBlocking(
/* callable= */ player::canSkipToPlaylistItem, /* defaultValueWhenException= */ false);
}
/**
* Returns whether {@link #skipToPreviousPlaylistItem()} is supported.
*
* @return {@code true} if supported. {@code false} otherwise.
*/
/* package */ boolean canSkipToPreviousPlaylistItem() {
return runPlayerCallableBlocking(
/* callable= */ player::canSkipToPreviousPlaylistItem,
/* defaultValueWhenException= */ false);
}
/**
* Returns whether {@link #skipToNextPlaylistItem()} is supported.
*
* @return {@code true} if supported. {@code false} otherwise.
*/
/* package */ boolean canSkipToNextPlaylistItem() {
return runPlayerCallableBlocking(
/* callable= */ player::canSkipToNextPlaylistItem, /* defaultValueWhenException= */ false);
}
/**
* Resets {@link SessionPlayerConnector} to its uninitialized state if not closed. After calling
* this method, you will have to initialize it again by setting the media item and calling {@link
* #prepare()}.
*
* <p>Note that if the player is closed, there is no way to reuse the instance.
*/
private void reset() {
// Cancel the pending commands.
playerCommandQueue.reset();
synchronized (stateLock) {
state = PLAYER_STATE_IDLE;
mediaItemToBuffState.clear();
}
this.<Void>runPlayerCallableBlocking(
/* callable= */ () -> {
player.reset();
return null;
});
}
private void setState(/* @PlayerState */ int state) {
boolean needToNotify = false;
synchronized (stateLock) {
if (this.state != state) {
this.state = state;
needToNotify = true;
}
}
if (needToNotify) {
notifySessionPlayerCallback(
callback -> callback.onPlayerStateChanged(SessionPlayerConnector.this, state));
}
}
private void setBufferingState(MediaItem item, /* @BuffState */ int state) {
@Nullable Integer previousState;
synchronized (stateLock) {
previousState = mediaItemToBuffState.put(item, state);
}
if (previousState == null || previousState != state) {
notifySessionPlayerCallback(
callback -> callback.onBufferingStateChanged(SessionPlayerConnector.this, item, state));
}
}
private void notifySessionPlayerCallback(SessionPlayerCallbackNotifier notifier) {
synchronized (stateLock) {
if (closed) {
return;
}
}
List<Pair<SessionPlayer.PlayerCallback, Executor>> callbacks = getCallbacks();
for (Pair<SessionPlayer.PlayerCallback, Executor> pair : callbacks) {
SessionPlayer.PlayerCallback callback = Assertions.checkNotNull(pair.first);
Executor executor = Assertions.checkNotNull(pair.second);
executor.execute(() -> notifier.callCallback(callback));
}
}
// TODO(internal b/160846312): Remove this suppress warnings and call onCurrentMediaItemChanged
// with a null item once we depend on media2 1.2.0.
@SuppressWarnings("nullness:argument.type.incompatible")
private void handlePlaylistChangedOnHandler() {
List<MediaItem> currentPlaylist = player.getPlaylist();
MediaMetadata playlistMetadata = player.getPlaylistMetadata();
MediaItem currentMediaItem = player.getCurrentMediaItem();
boolean notifyCurrentMediaItem =
!ObjectsCompat.equals(this.currentMediaItem, currentMediaItem) && currentMediaItem != null;
this.currentMediaItem = currentMediaItem;
long currentPosition = getCurrentPosition();
notifySessionPlayerCallback(
callback -> {
callback.onPlaylistChanged(
SessionPlayerConnector.this, currentPlaylist, playlistMetadata);
if (notifyCurrentMediaItem) {
callback.onCurrentMediaItemChanged(SessionPlayerConnector.this, currentMediaItem);
}
});
}
private void notifySkipToCompletedOnHandler() {
MediaItem currentMediaItem = Assertions.checkNotNull(player.getCurrentMediaItem());
if (ObjectsCompat.equals(this.currentMediaItem, currentMediaItem)) {
return;
}
this.currentMediaItem = currentMediaItem;
long currentPosition = getCurrentPosition();
notifySessionPlayerCallback(
callback -> {
callback.onCurrentMediaItemChanged(SessionPlayerConnector.this, currentMediaItem);
});
}
private <T> T runPlayerCallableBlocking(Callable<T> callable) {
SettableFuture<T> future = SettableFuture.create();
boolean success =
postOrRun(
taskHandler,
() -> {
try {
future.set(callable.call());
} catch (Throwable e) {
future.setException(e);
}
});
Assertions.checkState(success);
boolean wasInterrupted = false;
try {
while (true) {
try {
return future.get();
} catch (InterruptedException e) {
// We always wait for player calls to return.
wasInterrupted = true;
} catch (ExecutionException e) {
if (DEBUG) {
Log.d(TAG, "Internal player error", e);
}
throw new IllegalStateException(e.getCause());
}
}
} finally {
if (wasInterrupted) {
Thread.currentThread().interrupt();
}
}
}
@Nullable
private <T> T runPlayerCallableBlockingWithNullOnException(Callable<@NullableType T> callable) {
try {
return runPlayerCallableBlocking(callable);
} catch (Exception e) {
return null;
}
}
private <T> T runPlayerCallableBlocking(Callable<T> callable, T defaultValueWhenException) {
try {
return runPlayerCallableBlocking(callable);
} catch (Exception e) {
return defaultValueWhenException;
}
}
private interface SessionPlayerCallbackNotifier {
void callCallback(SessionPlayer.PlayerCallback callback);
}
private final class ExoPlayerWrapperListener implements PlayerWrapper.Listener {
@Override
public void onPlayerStateChanged(int playerState) {
setState(playerState);
if (playerState == PLAYER_STATE_PLAYING) {
playerCommandQueue.notifyCommandCompleted(PlayerCommandQueue.COMMAND_CODE_PLAYER_PLAY);
} else if (playerState == PLAYER_STATE_PAUSED) {
playerCommandQueue.notifyCommandCompleted(PlayerCommandQueue.COMMAND_CODE_PLAYER_PAUSE);
}
}
@Override
public void onPrepared(MediaItem mediaItem, int bufferingPercentage) {
Assertions.checkNotNull(mediaItem);
if (bufferingPercentage >= 100) {
setBufferingState(mediaItem, BUFFERING_STATE_COMPLETE);
} else {
setBufferingState(mediaItem, BUFFERING_STATE_BUFFERING_AND_PLAYABLE);
}
playerCommandQueue.notifyCommandCompleted(PlayerCommandQueue.COMMAND_CODE_PLAYER_PREPARE);
}
@Override
public void onSeekCompleted() {
long currentPosition = getCurrentPosition();
notifySessionPlayerCallback(
callback -> callback.onSeekCompleted(SessionPlayerConnector.this, currentPosition));
}
@Override
public void onBufferingStarted(MediaItem mediaItem) {
setBufferingState(mediaItem, BUFFERING_STATE_BUFFERING_AND_STARVED);
}
@Override
public void onBufferingUpdate(MediaItem mediaItem, int bufferingPercentage) {
if (bufferingPercentage >= 100) {
setBufferingState(mediaItem, BUFFERING_STATE_COMPLETE);
}
}
@Override
public void onBufferingEnded(MediaItem mediaItem, int bufferingPercentage) {
if (bufferingPercentage >= 100) {
setBufferingState(mediaItem, BUFFERING_STATE_COMPLETE);
} else {
setBufferingState(mediaItem, BUFFERING_STATE_BUFFERING_AND_PLAYABLE);
}
}
@Override
public void onCurrentMediaItemChanged(MediaItem mediaItem) {
if (ObjectsCompat.equals(currentMediaItem, mediaItem)) {
return;
}
currentMediaItem = mediaItem;
long currentPosition = getCurrentPosition();
notifySessionPlayerCallback(
callback -> {
callback.onCurrentMediaItemChanged(SessionPlayerConnector.this, mediaItem);
});
}
@Override
public void onPlaybackEnded() {
notifySessionPlayerCallback(
callback -> callback.onPlaybackCompleted(SessionPlayerConnector.this));
}
@Override
public void onError(@Nullable MediaItem mediaItem) {
playerCommandQueue.notifyCommandError();
if (mediaItem != null) {
setBufferingState(mediaItem, BUFFERING_STATE_UNKNOWN);
}
}
@Override
public void onPlaylistChanged() {
handlePlaylistChangedOnHandler();
}
@Override
public void onShuffleModeChanged(int shuffleMode) {
notifySessionPlayerCallback(
callback -> callback.onShuffleModeChanged(SessionPlayerConnector.this, shuffleMode));
}
@Override
public void onRepeatModeChanged(int repeatMode) {
notifySessionPlayerCallback(
callback -> callback.onRepeatModeChanged(SessionPlayerConnector.this, repeatMode));
}
@Override
public void onPlaybackSpeedChanged(float playbackSpeed) {
notifySessionPlayerCallback(
callback -> callback.onPlaybackSpeedChanged(SessionPlayerConnector.this, playbackSpeed));
}
@Override
public void onAudioAttributesChanged(AudioAttributesCompat audioAttributes) {
notifySessionPlayerCallback(
callback ->
callback.onAudioAttributesChanged(SessionPlayerConnector.this, audioAttributes));
}
}
}