/
MediaSession.java
2017 lines (1844 loc) · 82.6 KB
/
MediaSession.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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 androidx.media3.session;
import static androidx.annotation.VisibleForTesting.PRIVATE;
import static androidx.media3.common.util.Assertions.checkArgument;
import static androidx.media3.common.util.Assertions.checkNotNull;
import static androidx.media3.common.util.Assertions.checkState;
import static androidx.media3.session.SessionResult.RESULT_ERROR_NOT_SUPPORTED;
import static androidx.media3.session.SessionResult.RESULT_SUCCESS;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.view.KeyEvent;
import androidx.annotation.DoNotInline;
import androidx.annotation.GuardedBy;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.VisibleForTesting;
import androidx.core.app.NotificationCompat;
import androidx.media.MediaSessionManager.RemoteUserInfo;
import androidx.media3.common.AudioAttributes;
import androidx.media3.common.C;
import androidx.media3.common.DeviceInfo;
import androidx.media3.common.MediaItem;
import androidx.media3.common.MediaLibraryInfo;
import androidx.media3.common.MediaMetadata;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.PlaybackParameters;
import androidx.media3.common.Player;
import androidx.media3.common.Player.DiscontinuityReason;
import androidx.media3.common.Player.PositionInfo;
import androidx.media3.common.Player.RepeatMode;
import androidx.media3.common.Rating;
import androidx.media3.common.Timeline;
import androidx.media3.common.TrackSelectionParameters;
import androidx.media3.common.Tracks;
import androidx.media3.common.VideoSize;
import androidx.media3.common.util.BitmapLoader;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.common.util.Util;
import androidx.media3.datasource.DataSourceBitmapLoader;
import androidx.media3.session.MediaLibraryService.LibraryParams;
import androidx.media3.session.MediaLibraryService.MediaLibrarySession;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Longs;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
import java.util.HashMap;
import java.util.List;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
/**
* A session that allows a media app to expose its player functionality, information of the playlist
* and the media item currently being played to other processes including the Android framework and
* other apps. The common use cases are as follows:
*
* <ul>
* <li>Receiving and dispatching media key events (for instance Bluetooth/wired headset and remote
* control devices).
* <li>Publish media playback information and player commands to SystemUI (media notification) and
* Android Auto/Wear OS.
* <li>Separating UI process and playback process.
* </ul>
*
* <p>A session should be created when an app wants to publish media playback information or handle
* media key events. In general, an app only needs one session for all playback, though multiple
* sessions can be created to provide finer grain controls of media. See <a
* href="#MultipleSessions">Supporting Multiple Sessions</a> for details.
*
* <p>If an app wants to support playback when in the background, using a {@link
* MediaSessionService} is the preferred approach. See {@link MediaSessionService} for details.
*
* <p>Topics covered here:
*
* <ol>
* <li><a href="#SessionLifecycle">Session Lifecycle</a>
* <li><a href="#ThreadingModel">Threading Model</a>
* <li><a href="#KeyEvents">Media Key Events Mapping</a>
* <li><a href="#MultipleSessions">Supporting Multiple Sessions</a>
* <li><a href="#BackwardCompatibility">Backward Compatibility with Legacy Session APIs</a>
* <li><a href="#CompatibilityController">Backward Compatibility with Legacy Controller APIs</a>
* </ol>
*
* <h2 id="SessionLifecycle">Session Lifecycle</h2>
*
* <p>A session can be created by {@link Builder}. The owner of the session may pass its {@link
* #getToken() session token} to other processes to allow them to create a {@link MediaController}
* to interact with the session.
*
* <p>When a session receives playback commands, the session calls corresponding methods directly on
* the underlying player set by {@link Builder#Builder(Context, Player)} or {@link
* #setPlayer(Player)}.
*
* <p>When an app is finished performing playback it must call {@link #release()} to clean up the
* session and notify any controllers. The app is responsible for releasing the underlying player
* after releasing the session.
*
* <h2 id="ThreadingModel">Threading Model</h2>
*
* <p>The instances are thread safe, but must be used on a thread with a looper.
*
* <p>{@link Callback} methods will be called on the application thread associated with the {@link
* Player#getApplicationLooper() application looper} of the underlying player. When a new player is
* set by {@link #setPlayer}, the player must use the same application looper as the previous one.
*
* <p>The session listens to player events via {@link Player.Listener} and expects the callback
* methods to be called on the application thread. If the player violates the threading contract, an
* {@link IllegalStateException} will be thrown.
*
* <h2 id="KeyEvents">Media Key Events Mapping</h2>
*
* <p>When the session receives media key events they are mapped to a method call on the underlying
* player. The following table shows the mapping between the event key code and the {@link Player}
* method which is called.
*
* <table>
* <caption>Key code and corresponding Player API</caption>
* <tr>
* <th>Key code</th>
* <th>Player API</th>
* </tr>
* <tr>
* <td>{@link KeyEvent#KEYCODE_MEDIA_PLAY}</td>
* <td>{@link Player#play()}</td>
* </tr>
* <tr>
* <td>{@link KeyEvent#KEYCODE_MEDIA_PAUSE}</td>
* <td>{@link Player#pause()}</td>
* </tr>
* <tr>
* <td>
* <ul>
* <li>{@link KeyEvent#KEYCODE_MEDIA_PLAY_PAUSE}</li>
* <li>{@link KeyEvent#KEYCODE_HEADSETHOOK}</li>
* </ul>
* </td>
* <td>
* <ul>
* <li>For a single tap,
* <ul>
* <li>
* {@link Player#pause()} if {@link Player#getPlayWhenReady() playWhenReady} is
* {@code true}
* </li>
* <li>{@link Player#play()} otherwise</li>
* </ul>
* <li>In case the media key events are coming from another package ID than the package ID of
* the media app (events coming for instance from Bluetooth), a double tap generating two
* key events within a brief amount of time, is converted to {@link Player#seekToNext()}
* </li>
* </ul>
* </td>
* </tr>
* <tr>
* <td>{@link KeyEvent#KEYCODE_MEDIA_NEXT}</td>
* <td>{@link Player#seekToNext()}</td>
* </tr>
* <tr>
* <td>{@link KeyEvent#KEYCODE_MEDIA_PREVIOUS}</td>
* <td>{@link Player#seekToPrevious()}</td>
* </tr>
* <tr>
* <td>{@link KeyEvent#KEYCODE_MEDIA_STOP}</td>
* <td>{@link Player#stop()}</td>
* </tr>
* <tr>
* <td>{@link KeyEvent#KEYCODE_MEDIA_FAST_FORWARD}</td>
* <td>{@link Player#seekForward()}</td>
* </tr>
* <tr>
* <td>{@link KeyEvent#KEYCODE_MEDIA_REWIND}</td>
* <td>{@link Player#seekBack()}</td>
* </tr>
* </table>
*
* <h2 id="MultipleSessions">Supporting Multiple Sessions</h2>
*
* <p>Generally, multiple sessions aren't necessary for most media apps. One exception is if your
* app can play multiple media content at the same time, but only for the playback of video-only
* media or remote playback, since the <a
* href="https://developer.android.com/media/optimize/audio-focus">audio focus policy</a> recommends
* not playing multiple audio content at the same time. Also, keep in mind that multiple media
* sessions would make Android Auto and Bluetooth devices with display to show your app multiple
* times, because they list up media sessions, not media apps.
*
* <h2 id="BackwardCompatibility">Backward Compatibility with Legacy Session APIs</h2>
*
* <p>An active {@link MediaSessionCompat} is internally created with the session for backwards
* compatibility. It's used to handle incoming connections and commands from {@link
* MediaControllerCompat} instances, and helps to utilize existing APIs that are built with legacy
* media session APIs.
*
* <h2 id="CompatibilityController">Backward Compatibility with Legacy Controller APIs</h2>
*
* <p>In addition to {@link MediaController}, the session also supports connections from the legacy
* controller APIs - {@linkplain android.media.session.MediaController framework controller} and
* {@linkplain MediaControllerCompat AndroidX controller compat}. However, {@link ControllerInfo}
* may not be precise for legacy controllers. See {@link ControllerInfo} for the details.
*
* <p>Neither an unknown package name nor an unknown UID mean that you should disallow a connection
* or commands per se. For SDK levels where such issues happen, session tokens can only be obtained
* by trusted controllers (e.g. Bluetooth, Auto, ...). This means only trusted controllers can
* connect and an app can accept such controllers in the same way as with legacy sessions.
*/
@DoNotMock
public class MediaSession {
static {
MediaLibraryInfo.registerModule("media3.session");
}
// It's better to have private static lock instead of using MediaSession.class because the
// private lock object isn't exposed.
private static final Object STATIC_LOCK = new Object();
// Note: This checks the uniqueness of a session ID only in single process.
// When the framework becomes able to check the uniqueness, this logic should be removed.
@GuardedBy("STATIC_LOCK")
private static final HashMap<String, MediaSession> SESSION_ID_TO_SESSION_MAP = new HashMap<>();
/**
* A builder for {@link MediaSession}.
*
* <p>Any incoming requests from the {@link MediaController} will be handled on the application
* thread of the underlying {@link Player}.
*/
public static final class Builder extends BuilderBase<MediaSession, Builder, Callback> {
/**
* Creates a builder for {@link MediaSession}.
*
* @param context The context.
* @param player The underlying player to perform playback and handle player commands.
* @throws IllegalArgumentException if {@link Player#canAdvertiseSession()} returns false.
*/
public Builder(Context context, Player player) {
super(context, player, new Callback() {});
}
/**
* Sets a {@link PendingIntent} to launch an {@link android.app.Activity} for the {@link
* MediaSession}. This can be used as a quick link to an ongoing media screen.
*
* <p>A client can use this pending intent to start an activity belonging to this session. On
* API levels below 33 the pending intent can be used {@linkplain
* NotificationCompat.Builder#setContentIntent(PendingIntent) as the content intent}. Tapping
* the notification will then send that pending intent and open the activity (see <a
* href="https://developer.android.com/training/notify-user/navigation">'Start an Activity from
* a Notification'</a>). For API levels starting with 33, the media notification reads the
* pending intent directly from the session.
*
* @param pendingIntent The pending intent.
* @return The builder to allow chaining.
*/
@Override
public Builder setSessionActivity(PendingIntent pendingIntent) {
return super.setSessionActivity(pendingIntent);
}
/**
* Sets an ID of the {@link MediaSession}. If not set, an empty string will be used.
*
* <p>Use this if and only if your app supports multiple playback at the same time and also
* wants to provide external apps to have finer-grained controls.
*
* @param id The ID. Must be unique among all {@link MediaSession sessions} per package.
* @return The builder to allow chaining.
*/
// Note: This ID is not visible to the controllers. ID is introduced in order to prevent
// apps from creating multiple sessions without any clear reasons. If they create two
// sessions with the same ID in a process, then an IllegalStateException will be thrown.
@Override
public Builder setId(String id) {
return super.setId(id);
}
/**
* Sets a callback for the {@link MediaSession} to handle incoming requests from {link
* MediaController}.
*
* <p>Apps that want to allow controllers to {@linkplain MediaController#setMediaItems(List)
* set} or {@linkplain MediaController#addMediaItems(List) add} media items to the playlist,
* must use a callback and override its {@link
* MediaSession.Callback#onSetMediaItems(MediaSession, ControllerInfo, List, int, long)} or
* {@link MediaSession.Callback#onSetMediaItems(MediaSession, ControllerInfo, List, int, long)}
* methods.
*
* @param callback The callback.
* @return The builder to allow chaining.
*/
@Override
public Builder setCallback(Callback callback) {
return super.setCallback(callback);
}
/**
* Sets an extras {@link Bundle} for the {@linkplain MediaSession#getToken() session token}. If
* not set, {@link Bundle#EMPTY} is used.
*
* <p>A controller has access to these extras through the {@linkplain
* MediaController#getConnectedToken() connected token}.
*
* @param tokenExtras The extras {@link Bundle}.
* @return The builder to allow chaining.
*/
@Override
public Builder setExtras(Bundle tokenExtras) {
return super.setExtras(tokenExtras);
}
/**
* Sets the {@linkplain MediaSession#getSessionExtras() session extras}. If not set, {@link
* Bundle#EMPTY} is used.
*
* <p>A controller has access to session extras through {@linkplain
* MediaController#getSessionExtras()}.
*
* @param sessionExtras The session extras {@link Bundle}.
* @return The builder to allow chaining.
*/
@UnstableApi
@Override
public Builder setSessionExtras(Bundle sessionExtras) {
return super.setSessionExtras(sessionExtras);
}
/**
* Sets a {@link BitmapLoader} for the {@link MediaSession} to decode bitmaps from compressed
* binary data or load bitmaps from {@link Uri}.
*
* <p>The provided instance will likely be called repeatedly with the same request, so it would
* be best if any provided instance does some caching. Simple caching can be added to any {@link
* BitmapLoader} implementation by wrapping it in {@link CacheBitmapLoader} before passing it to
* this method.
*
* <p>If no instance is set, a {@link CacheBitmapLoader} with a {@link DataSourceBitmapLoader}
* inside will be used.
*
* @param bitmapLoader The bitmap loader {@link BitmapLoader}.
* @return The builder to allow chaining.
*/
@UnstableApi
@Override
public Builder setBitmapLoader(BitmapLoader bitmapLoader) {
return super.setBitmapLoader(bitmapLoader);
}
/**
* Sets the custom layout of the session.
*
* <p>The button are converted to custom actions in the legacy media session playback state for
* legacy controllers (see {@code
* PlaybackStateCompat.Builder#addCustomAction(PlaybackStateCompat.CustomAction)}). When
* converting, the {@linkplain SessionCommand#customExtras custom extras of the session command}
* is used for the extras of the legacy custom action.
*
* <p>Controllers that connect have the custom layout of the session available with the initial
* connection result by default. A custom layout specific to a controller can be set when the
* controller {@linkplain MediaSession.Callback#onConnect connects} by using an {@link
* ConnectionResult.AcceptedResultBuilder}.
*
* <p>Use {@code MediaSession.setCustomLayout(..)} to update the custom layout during the life
* time of the session.
*
* @param customLayout The ordered list of {@link CommandButton command buttons}.
* @return The builder to allow chaining.
*/
@UnstableApi
@Override
public Builder setCustomLayout(List<CommandButton> customLayout) {
return super.setCustomLayout(customLayout);
}
/**
* Sets whether periodic position updates should be sent to controllers while playing. If false,
* no periodic position updates are sent to controllers.
*
* <p>The default is {@code true}.
*
* @param isEnabled Whether periodic position update is enabled.
*/
@UnstableApi
@Override
public Builder setPeriodicPositionUpdateEnabled(boolean isEnabled) {
return super.setPeriodicPositionUpdateEnabled(isEnabled);
}
/**
* Sets whether a play button is shown if playback is {@linkplain
* Player#getPlaybackSuppressionReason() suppressed}.
*
* <p>The default is {@code true}.
*
* @param showPlayButtonIfPlaybackIsSuppressed Whether to show a play button if playback is
* {@linkplain Player#getPlaybackSuppressionReason() suppressed}.
*/
@UnstableApi
@Override
public Builder setShowPlayButtonIfPlaybackIsSuppressed(
boolean showPlayButtonIfPlaybackIsSuppressed) {
return super.setShowPlayButtonIfPlaybackIsSuppressed(showPlayButtonIfPlaybackIsSuppressed);
}
/**
* Builds a {@link MediaSession}.
*
* @return A new session.
* @throws IllegalStateException if a {@link MediaSession} with the same {@link #setId(String)
* ID} already exists in the package.
*/
@Override
public MediaSession build() {
if (bitmapLoader == null) {
bitmapLoader = new CacheBitmapLoader(new DataSourceBitmapLoader(context));
}
return new MediaSession(
context,
id,
player,
sessionActivity,
customLayout,
callback,
tokenExtras,
sessionExtras,
checkNotNull(bitmapLoader),
playIfSuppressed,
isPeriodicPositionUpdateEnabled);
}
}
/** Information of a {@link MediaController} or a {@link MediaBrowser}. */
public static final class ControllerInfo {
/** The {@linkplain #getControllerVersion() controller version} of legacy controllers. */
public static final int LEGACY_CONTROLLER_VERSION = 0;
/** The {@linkplain #getInterfaceVersion()} interface version} of legacy controllers. */
@UnstableApi public static final int LEGACY_CONTROLLER_INTERFACE_VERSION = 0;
private final RemoteUserInfo remoteUserInfo;
private final int libraryVersion;
private final int interfaceVersion;
private final boolean isTrusted;
@Nullable private final ControllerCb controllerCb;
private final Bundle connectionHints;
/**
* Creates an instance.
*
* @param remoteUserInfo The remote user info.
* @param trusted {@code true} if trusted, {@code false} otherwise.
* @param cb ControllerCb. Can be {@code null} only when a MediaBrowserCompat connects to
* MediaSessionService and ControllerInfo is needed for {@link
* MediaSession.Callback#onConnect(MediaSession, ControllerInfo)}.
* @param connectionHints A session-specific argument sent from the controller for the
* connection. The contents of this bundle may affect the connection result.
*/
/* package */ ControllerInfo(
RemoteUserInfo remoteUserInfo,
int libraryVersion,
int interfaceVersion,
boolean trusted,
@Nullable ControllerCb cb,
Bundle connectionHints) {
this.remoteUserInfo = remoteUserInfo;
this.libraryVersion = libraryVersion;
this.interfaceVersion = interfaceVersion;
isTrusted = trusted;
controllerCb = cb;
this.connectionHints = connectionHints;
}
/* package */ RemoteUserInfo getRemoteUserInfo() {
return remoteUserInfo;
}
/**
* Returns the library version of the controller.
*
* <p>It will be the same as {@link MediaLibraryInfo#VERSION_INT} of the controller, or less
* than {@code 1000000} if the controller is a legacy controller.
*/
public int getControllerVersion() {
return libraryVersion;
}
/** Returns the interface version of the controller, or 0 if it's a legacy controller. */
@UnstableApi
public int getInterfaceVersion() {
return interfaceVersion;
}
/**
* Returns the package name. Can be {@link RemoteUserInfo#LEGACY_CONTROLLER} for
* interoperability.
*
* <p>Interoperability: Package name may not be precisely obtained for legacy controller API on
* older device. Here are details.
*
* <table>
* <caption>Summary when package name isn't precise</caption>
* <tr><th>SDK version when package name isn't precise</th>
* <th>{@code ControllerInfo#getPackageName()} for legacy controller</th>
* <tr><td>{@code SDK_INT < 21}</td>
* <td>Actual package name via {@link PackageManager#getNameForUid} with UID.<br>
* It's sufficient for most cases, but doesn't precisely distinguish caller if it
* uses shared user ID.</td>
* <tr><td>{@code 21 <= SDK_INT < 24}</td>
* <td>{@link RemoteUserInfo#LEGACY_CONTROLLER}</td>
* </table>
*/
public String getPackageName() {
return remoteUserInfo.getPackageName();
}
/**
* Returns the UID of the controller. Can be a negative value for interoperability.
*
* <p>Interoperability: If {@code 21 <= SDK_INT < 28}, then UID would be a negative value
* because it cannot be obtained.
*/
public int getUid() {
return remoteUserInfo.getUid();
}
/** Returns the connection hints sent from controller. */
public Bundle getConnectionHints() {
return new Bundle(connectionHints);
}
/**
* Returns if the controller has been granted {@code android.permission.MEDIA_CONTENT_CONTROL}
* or has an enabled notification listener so it can be trusted to accept connection and
* incoming command requests.
*/
@UnstableApi
public boolean isTrusted() {
return isTrusted;
}
@Override
public int hashCode() {
return Objects.hashCode(controllerCb, remoteUserInfo);
}
@Override
public boolean equals(@Nullable Object obj) {
if (!(obj instanceof ControllerInfo)) {
return false;
}
if (this == obj) {
return true;
}
ControllerInfo other = (ControllerInfo) obj;
if (controllerCb != null || other.controllerCb != null) {
return Util.areEqual(controllerCb, other.controllerCb);
}
return remoteUserInfo.equals(other.remoteUserInfo);
}
@Override
public String toString() {
return "ControllerInfo {pkg="
+ remoteUserInfo.getPackageName()
+ ", uid="
+ remoteUserInfo.getUid()
+ "})";
}
@Nullable
/* package */ ControllerCb getControllerCb() {
return controllerCb;
}
/* package */ static ControllerInfo createLegacyControllerInfo() {
RemoteUserInfo legacyRemoteUserInfo =
new RemoteUserInfo(
RemoteUserInfo.LEGACY_CONTROLLER,
/* pid= */ RemoteUserInfo.UNKNOWN_PID,
/* uid= */ RemoteUserInfo.UNKNOWN_UID);
return new ControllerInfo(
legacyRemoteUserInfo,
ControllerInfo.LEGACY_CONTROLLER_VERSION,
ControllerInfo.LEGACY_CONTROLLER_INTERFACE_VERSION,
/* trusted= */ false,
/* cb= */ null,
/* connectionHints= */ Bundle.EMPTY);
}
/** Returns a {@link ControllerInfo} suitable for use when testing client code. */
@VisibleForTesting(otherwise = PRIVATE)
public static ControllerInfo createTestOnlyControllerInfo(
RemoteUserInfo remoteUserInfo,
int libraryVersion,
int interfaceVersion,
boolean trusted,
Bundle connectionHints) {
return new MediaSession.ControllerInfo(
remoteUserInfo,
libraryVersion,
interfaceVersion,
trusted,
/* cb= */ null,
connectionHints);
}
}
private final MediaSessionImpl impl;
// Suppress nullness check as `this` is under initialization.
@SuppressWarnings({"nullness:argument", "nullness:method.invocation"})
/* package */ MediaSession(
Context context,
String id,
Player player,
@Nullable PendingIntent sessionActivity,
ImmutableList<CommandButton> customLayout,
Callback callback,
Bundle tokenExtras,
Bundle sessionExtras,
BitmapLoader bitmapLoader,
boolean playIfSuppressed,
boolean isPeriodicPositionUpdateEnabled) {
synchronized (STATIC_LOCK) {
if (SESSION_ID_TO_SESSION_MAP.containsKey(id)) {
throw new IllegalStateException("Session ID must be unique. ID=" + id);
}
SESSION_ID_TO_SESSION_MAP.put(id, this);
}
impl =
createImpl(
context,
id,
player,
sessionActivity,
customLayout,
callback,
tokenExtras,
sessionExtras,
bitmapLoader,
playIfSuppressed,
isPeriodicPositionUpdateEnabled);
}
/* package */ MediaSessionImpl createImpl(
Context context,
String id,
Player player,
@Nullable PendingIntent sessionActivity,
ImmutableList<CommandButton> customLayout,
Callback callback,
Bundle tokenExtras,
Bundle sessionExtras,
BitmapLoader bitmapLoader,
boolean playIfSuppressed,
boolean isPeriodicPositionUpdateEnabled) {
return new MediaSessionImpl(
this,
context,
id,
player,
sessionActivity,
customLayout,
callback,
tokenExtras,
sessionExtras,
bitmapLoader,
playIfSuppressed,
isPeriodicPositionUpdateEnabled);
}
/* package */ MediaSessionImpl getImpl() {
return impl;
}
@Nullable
/* package */ static MediaSession getSession(Uri sessionUri) {
synchronized (STATIC_LOCK) {
for (MediaSession session : SESSION_ID_TO_SESSION_MAP.values()) {
if (Util.areEqual(session.getUri(), sessionUri)) {
return session;
}
}
}
return null;
}
/**
* Returns the {@link PendingIntent} to launch {@linkplain
* Builder#setSessionActivity(PendingIntent) the session activity} or null if not set.
*
* @return The {@link PendingIntent} to launch an activity belonging to the session.
*/
@Nullable
public final PendingIntent getSessionActivity() {
return impl.getSessionActivity();
}
/**
* Updates the session activity that was set when {@linkplain
* Builder#setSessionActivity(PendingIntent) building the session}.
*
* @param activityPendingIntent The pending intent to start the session activity.
*/
@UnstableApi
public final void setSessionActivity(PendingIntent activityPendingIntent) {
if (Util.SDK_INT >= 31) {
checkArgument(Api31.isActivity(activityPendingIntent));
}
impl.setSessionActivity(activityPendingIntent);
}
/**
* Sets the underlying {@link Player} for this session to dispatch incoming events to.
*
* @param player A player that handles actual media playback in your app.
* @throws IllegalArgumentException if the new player's application looper differs from the
* current player's looper, or {@link Player#canAdvertiseSession()} returns false.
* @throws IllegalStateException if the new player's application looper differs from the current
* looper.
*/
public final void setPlayer(Player player) {
checkNotNull(player);
checkArgument(player.canAdvertiseSession());
checkArgument(player.getApplicationLooper() == getPlayer().getApplicationLooper());
checkState(player.getApplicationLooper() == Looper.myLooper());
impl.setPlayer(player);
}
/**
* Releases the session and disconnects all connected controllers.
*
* <p>The session must not be used after calling this method.
*
* <p>Releasing the session removes the session's listeners from the player but does not
* {@linkplain Player#stop() stop} or {@linkplain Player#release() release} the player. An app can
* further use the player after the session is released and needs to make sure to eventually
* release the player.
*/
public final void release() {
try {
synchronized (STATIC_LOCK) {
SESSION_ID_TO_SESSION_MAP.remove(impl.getId());
}
impl.release();
} catch (Exception e) {
// Should not be here.
}
}
/* package */ final boolean isReleased() {
return impl.isReleased();
}
/** Returns the underlying {@link Player}. */
public final Player getPlayer() {
return impl.getPlayerWrapper().getWrappedPlayer();
}
/** Returns the session ID. */
public final String getId() {
return impl.getId();
}
/** Returns the {@link SessionToken} for creating {@link MediaController}. */
public final SessionToken getToken() {
return impl.getToken();
}
/** Returns the list of connected controllers. */
public final List<ControllerInfo> getConnectedControllers() {
return impl.getConnectedControllers();
}
/**
* Returns the {@link ControllerInfo} for the controller that sent the current request for a
* {@link Player} method.
*
* <p>This method will return a non-null value while {@link Player} methods triggered by a
* controller are executed.
*
* <p>Note: If you want to prevent a controller from calling a method, specify the {@link
* ConnectionResult#availablePlayerCommands available commands} in {@link Callback#onConnect} or
* set them via {@link #setAvailableCommands}.
*
* <p>This method must be called on the {@linkplain Player#getApplicationLooper() application
* thread} of the underlying player.
*
* @return The {@link ControllerInfo} of the controller that sent the current request, or {@code
* null} if not applicable.
*/
@Nullable
public final ControllerInfo getControllerForCurrentRequest() {
return impl.getControllerForCurrentRequest();
}
/**
* Returns whether the given media controller info belongs to the media notification controller.
*
* <p>See {@link #getMediaNotificationControllerInfo()}.
*
* @param controllerInfo The controller info.
* @return Whether the controller info belongs to the media notification controller.
*/
@UnstableApi
public boolean isMediaNotificationController(ControllerInfo controllerInfo) {
return impl.isMediaNotificationController(controllerInfo);
}
/**
* Returns the {@link ControllerInfo} of the media notification controller.
*
* <p>Use this controller info to set {@linkplain #setAvailableCommands(ControllerInfo,
* SessionCommands, Player.Commands) available commands} and {@linkplain
* #setCustomLayout(ControllerInfo, List) custom layout} that are consistently applied to the
* media notification on all API levels.
*
* <p>Available {@linkplain SessionCommands session commands} of the media notification controller
* are used to enable or disable buttons of the custom layout before it is passed to the
* {@linkplain MediaNotification.Provider#createNotification(MediaSession, ImmutableList,
* MediaNotification.ActionFactory, MediaNotification.Provider.Callback) notification provider}.
* Disabled command buttons are not converted to notification actions when using {@link
* DefaultMediaNotificationProvider}. This affects the media notification displayed by System UI
* below API 33.
*
* <p>The available session commands of the media notification controller are used to maintain
* custom actions of the platform session (see {@code PlaybackStateCompat.getCustomActions()}).
* Command buttons of the custom layout are disabled or enabled according to the available session
* commands. Disabled command buttons are not converted to custom actions of the platform session.
* This affects the media notification displayed by System UI <a
* href="https://developer.android.com/about/versions/13/behavior-changes-13#playback-controls">starting
* with API 33</a>.
*
* <p>The available {@linkplain Player.Commands player commands} are intersected with the actual
* available commands of the underlying player to determine the playback actions of the platform
* session (see {@code PlaybackStateCompat.getActions()}).
*/
@UnstableApi
@Nullable
public ControllerInfo getMediaNotificationControllerInfo() {
return impl.getMediaNotificationControllerInfo();
}
/**
* Returns whether the given {@link ControllerInfo} belongs to an Automotive OS controller.
*
* <p>Note: This is not a security validation.
*
* @param controllerInfo The controller info of the connected controller.
* @return True if the controller into belongs to a connected Automotive OS controller.
*/
@UnstableApi
public final boolean isAutomotiveController(ControllerInfo controllerInfo) {
return impl.isAutomotiveController(controllerInfo);
}
/**
* Returns whether the given {@link ControllerInfo} belongs to an Android Auto companion app
* controller.
*
* <p>Note: This is not a security validation.
*
* @param controllerInfo The controller info of the connected controller.
* @return True if the controller into belongs to a connected Auto companion client app.
*/
@UnstableApi
public final boolean isAutoCompanionController(ControllerInfo controllerInfo) {
return impl.isAutoCompanionController(controllerInfo);
}
/**
* Sets the custom layout for the given Media3 controller.
*
* <p>Make sure to have the session commands of all command buttons of the custom layout
* {@linkplain MediaController#getAvailableSessionCommands() available for controllers}. Include
* the custom session commands a controller should be able to send in the available commands of
* the connection result {@linkplain MediaSession.Callback#onConnect(MediaSession, ControllerInfo)
* that your app returns when the controller connects}. The {@link CommandButton#isEnabled} flag
* is set according to the available commands of the controller and overrides a value that may
* have been set by the app.
*
* <p>On the controller side, {@link
* MediaController.Listener#onCustomLayoutChanged(MediaController, List)} is only called if the
* new custom layout is different to the custom layout the {@link
* MediaController#getCustomLayout() controller already has available}. Note that this comparison
* uses {@link CommandButton#equals} and therefore ignores {@link CommandButton#extras}.
*
* <p>It's up to controller's decision how to represent the layout in its own UI.
*
* <p>Interoperability: This call has no effect when called for a {@linkplain
* ControllerInfo#LEGACY_CONTROLLER_VERSION legacy controller}.
*
* @param controller The controller for which to set the custom layout.
* @param layout The ordered list of {@linkplain CommandButton command buttons}.
*/
@CanIgnoreReturnValue
public final ListenableFuture<SessionResult> setCustomLayout(
ControllerInfo controller, List<CommandButton> layout) {
checkNotNull(controller, "controller must not be null");
checkNotNull(layout, "layout must not be null");
return impl.setCustomLayout(controller, ImmutableList.copyOf(layout));
}
/**
* Sets the custom layout that can initially be set when building the session.
*
* <p>Calling this method broadcasts the custom layout to all connected Media3 controllers,
* including the {@linkplain #getMediaNotificationControllerInfo() media notification controller}.
*
* <p>On the controller side, the {@linkplain CommandButton#isEnabled enabled} flag is set
* according to the available commands of the controller which overrides a value that has been set
* by the session.
*
* <p>{@link MediaController.Listener#onCustomLayoutChanged(MediaController, List)} is only called
* if the new custom layout is different to the custom layout the {@linkplain
* MediaController#getCustomLayout() controller already has available}. Note that {@link Bundle
* extras} are ignored when comparing {@linkplain CommandButton command buttons}.
*
* <p>Controllers that connect after calling this method will have the new custom layout available
* with the initial connection result. A custom layout specific to a controller can be set when
* the controller {@linkplain MediaSession.Callback#onConnect connects} by using an {@link
* ConnectionResult.AcceptedResultBuilder}.
*
* @param layout The ordered list of {@link CommandButton}.
*/
public final void setCustomLayout(List<CommandButton> layout) {
checkNotNull(layout, "layout must not be null");
impl.setCustomLayout(ImmutableList.copyOf(layout));
}
/**
* Sets the new available commands for the controller.
*
* <p>This is a synchronous call. Changes in the available commands take effect immediately
* regardless of the controller notified about the change through {@link
* Player.Listener#onAvailableCommandsChanged(Player.Commands)} and {@link
* MediaController.Listener#onAvailableSessionCommandsChanged(MediaController, SessionCommands)}.
*
* <p>Note that {@code playerCommands} will be intersected with the {@link
* Player#getAvailableCommands() available commands} of the underlying {@link Player} and the
* controller will only be able to call the commonly available commands.
*
* @param controller The controller to change allowed commands.
* @param sessionCommands The new available session commands.
* @param playerCommands The new available player commands.
*/
public final void setAvailableCommands(
ControllerInfo controller, SessionCommands sessionCommands, Player.Commands playerCommands) {
checkNotNull(controller, "controller must not be null");
checkNotNull(sessionCommands, "sessionCommands must not be null");
checkNotNull(playerCommands, "playerCommands must not be null");
impl.setAvailableCommands(controller, sessionCommands, playerCommands);
}
/**
* Returns the custom layout of the session.
*
* <p>For informational purpose only. Mutations on the {@link Bundle} of either a {@link
* CommandButton} or a {@link SessionCommand} do not have effect. To change the custom layout use
* {@link #setCustomLayout(List)} or {@link #setCustomLayout(ControllerInfo, List)}.
*/
@UnstableApi
public ImmutableList<CommandButton> getCustomLayout() {
return impl.getCustomLayout();
}
/**
* Broadcasts a custom command to all connected controllers.
*
* <p>This is a synchronous call and doesn't wait for results from the controllers.
*
* <p>A command is not accepted if it is not a custom command.
*
* @param command A custom command.