• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.car.media.common.playback;
18 
19 import static androidx.lifecycle.Transformations.switchMap;
20 
21 import static com.android.car.arch.common.LiveDataFunctions.dataOf;
22 import static com.android.car.media.common.playback.PlaybackStateAnnotations.Actions;
23 
24 import android.annotation.IntDef;
25 import android.annotation.NonNull;
26 import android.annotation.Nullable;
27 import android.app.Application;
28 import android.content.Context;
29 import android.content.pm.PackageManager;
30 import android.content.res.Resources;
31 import android.graphics.drawable.Drawable;
32 import android.media.MediaMetadata;
33 import android.os.Bundle;
34 import android.support.v4.media.MediaMetadataCompat;
35 import android.support.v4.media.RatingCompat;
36 import android.support.v4.media.session.MediaControllerCompat;
37 import android.support.v4.media.session.MediaSessionCompat;
38 import android.support.v4.media.session.PlaybackStateCompat;
39 import android.util.Log;
40 
41 import androidx.lifecycle.AndroidViewModel;
42 import androidx.lifecycle.LiveData;
43 import androidx.lifecycle.MutableLiveData;
44 import androidx.lifecycle.Observer;
45 
46 import com.android.car.media.common.CustomPlaybackAction;
47 import com.android.car.media.common.MediaConstants;
48 import com.android.car.media.common.MediaItemMetadata;
49 import com.android.car.media.common.R;
50 import com.android.car.media.common.source.MediaSourceColors;
51 import com.android.car.media.common.source.MediaSourceViewModel;
52 import com.android.internal.annotations.VisibleForTesting;
53 
54 import java.lang.annotation.Retention;
55 import java.lang.annotation.RetentionPolicy;
56 import java.util.ArrayList;
57 import java.util.Collections;
58 import java.util.List;
59 import java.util.Objects;
60 import java.util.stream.Collectors;
61 
62 /**
63  * ViewModel for media playback.
64  * <p>
65  * Observes changes to the provided MediaController to expose playback state and metadata
66  * observables.
67  * <p>
68  * PlaybackViewModel is a singleton tied to the application to provide a single source of truth.
69  */
70 public class PlaybackViewModel extends AndroidViewModel {
71     private static final String TAG = "PlaybackViewModel";
72 
73     private static final String ACTION_SET_RATING =
74             "com.android.car.media.common.ACTION_SET_RATING";
75     private static final String EXTRA_SET_HEART = "com.android.car.media.common.EXTRA_SET_HEART";
76 
77     private static PlaybackViewModel sInstance;
78 
79     /** Returns the PlaybackViewModel singleton tied to the application. */
get(@onNull Application application)80     public static PlaybackViewModel get(@NonNull Application application) {
81         if (sInstance == null) {
82             sInstance = new PlaybackViewModel(application);
83         }
84         return sInstance;
85     }
86 
87     /**
88      * Possible main actions.
89      */
90     @IntDef({ACTION_PLAY, ACTION_STOP, ACTION_PAUSE, ACTION_DISABLED})
91     @Retention(RetentionPolicy.SOURCE)
92     public @interface Action {
93     }
94 
95     /**
96      * Main action is disabled. The source can't play media at this time
97      */
98     public static final int ACTION_DISABLED = 0;
99     /**
100      * Start playing
101      */
102     public static final int ACTION_PLAY = 1;
103     /**
104      * Stop playing
105      */
106     public static final int ACTION_STOP = 2;
107     /**
108      * Pause playing
109      */
110     public static final int ACTION_PAUSE = 3;
111 
112     /** Needs to be a MediaMetadata because the compat class doesn't implement equals... */
113     private static final MediaMetadata EMPTY_MEDIA_METADATA = new MediaMetadata.Builder().build();
114 
115     private final MediaControllerCallback mMediaControllerCallback = new MediaControllerCallback();
116     private final Observer<MediaControllerCompat> mMediaControllerObserver =
117             mMediaControllerCallback::onMediaControllerChanged;
118 
119     private final MediaSourceColors.Factory mColorsFactory;
120     private final MutableLiveData<MediaSourceColors> mColors = dataOf(null);
121 
122     private final MutableLiveData<MediaItemMetadata> mMetadata = dataOf(null);
123 
124     // Filters out queue items with no description or title and converts them to MediaItemMetadata
125     private final MutableLiveData<List<MediaItemMetadata>> mSanitizedQueue = dataOf(null);
126 
127     private final MutableLiveData<Boolean> mHasQueue = dataOf(null);
128 
129     private final MutableLiveData<CharSequence> mQueueTitle = dataOf(null);
130 
131     private final MutableLiveData<PlaybackController> mPlaybackControls = dataOf(null);
132 
133     private final MutableLiveData<PlaybackStateWrapper> mPlaybackStateWrapper = dataOf(null);
134 
135     private final LiveData<PlaybackProgress> mProgress =
136             switchMap(mPlaybackStateWrapper,
137                     state -> state == null ? dataOf(new PlaybackProgress(0L, 0L))
138                             : new ProgressLiveData(state.mState, state.getMaxProgress()));
139 
PlaybackViewModel(Application application)140     private PlaybackViewModel(Application application) {
141         this(application, MediaSourceViewModel.get(application).getMediaController());
142     }
143 
144     @VisibleForTesting
PlaybackViewModel(Application application, LiveData<MediaControllerCompat> controller)145     public PlaybackViewModel(Application application, LiveData<MediaControllerCompat> controller) {
146         super(application);
147         mColorsFactory = new MediaSourceColors.Factory(application);
148         controller.observeForever(mMediaControllerObserver);
149     }
150 
151     /**
152      * Returns a LiveData that emits the colors for the currently set media source.
153      */
getMediaSourceColors()154     public LiveData<MediaSourceColors> getMediaSourceColors() {
155         return mColors;
156     }
157 
158     /**
159      * Returns a LiveData that emits a MediaItemMetadata of the current media item in the session
160      * managed by the provided {@link MediaControllerCompat}.
161      */
getMetadata()162     public LiveData<MediaItemMetadata> getMetadata() {
163         return mMetadata;
164     }
165 
166     /**
167      * Returns a LiveData that emits the current queue as MediaItemMetadatas where items without a
168      * title have been filtered out.
169      */
getQueue()170     public LiveData<List<MediaItemMetadata>> getQueue() {
171         return mSanitizedQueue;
172     }
173 
174     /**
175      * Returns a LiveData that emits whether the MediaController has a non-empty queue
176      */
hasQueue()177     public LiveData<Boolean> hasQueue() {
178         return mHasQueue;
179     }
180 
181     /**
182      * Returns a LiveData that emits the current queue title.
183      */
getQueueTitle()184     public LiveData<CharSequence> getQueueTitle() {
185         return mQueueTitle;
186     }
187 
188     /**
189      * Returns a LiveData that emits an object for controlling the currently selected
190      * MediaController.
191      */
getPlaybackController()192     public LiveData<PlaybackController> getPlaybackController() {
193         return mPlaybackControls;
194     }
195 
196     /** Returns a {@PlaybackStateWrapper} live data. */
getPlaybackStateWrapper()197     public LiveData<PlaybackStateWrapper> getPlaybackStateWrapper() {
198         return mPlaybackStateWrapper;
199     }
200 
201     /**
202      * Returns a LiveData that emits the current playback progress, in milliseconds. This is a
203      * value between 0 and {@link #getPlaybackStateWrapper#getMaxProgress()} or
204      * {@link PlaybackStateCompat#PLAYBACK_POSITION_UNKNOWN} if the current position is unknown.
205      * This value will update on its own periodically (less than a second) while active.
206      */
getProgress()207     public LiveData<PlaybackProgress> getProgress() {
208         return mProgress;
209     }
210 
211     @VisibleForTesting
getMediaController()212     MediaControllerCompat getMediaController() {
213         return mMediaControllerCallback.mMediaController;
214     }
215 
216     @VisibleForTesting
getMediaMetadata()217     MediaMetadataCompat getMediaMetadata() {
218         return mMediaControllerCallback.mMediaMetadata;
219     }
220 
221 
222     private class MediaControllerCallback extends MediaControllerCompat.Callback {
223 
224         private MediaControllerCompat mMediaController;
225         private MediaMetadataCompat mMediaMetadata;
226         private PlaybackStateCompat mPlaybackState;
227 
onMediaControllerChanged(MediaControllerCompat controller)228         void onMediaControllerChanged(MediaControllerCompat controller) {
229             if (mMediaController == controller) {
230                 Log.w(TAG, "onMediaControllerChanged noop");
231                 return;
232             }
233 
234             if (mMediaController != null) {
235                 mMediaController.unregisterCallback(this);
236             }
237 
238             mMediaMetadata = null;
239             mPlaybackState = null;
240             mMediaController = controller;
241             mPlaybackControls.setValue(new PlaybackController(controller));
242 
243             if (mMediaController != null) {
244                 mMediaController.registerCallback(this);
245 
246                 mColors.setValue(mColorsFactory.extractColors(controller.getPackageName()));
247 
248                 // The apps don't always send updates so make sure we fetch the most recent values.
249                 onMetadataChanged(mMediaController.getMetadata());
250                 onPlaybackStateChanged(mMediaController.getPlaybackState());
251                 onQueueChanged(mMediaController.getQueue());
252                 onQueueTitleChanged(mMediaController.getQueueTitle());
253             } else {
254                 mColors.setValue(null);
255                 onMetadataChanged(null);
256                 onPlaybackStateChanged(null);
257                 onQueueChanged(null);
258                 onQueueTitleChanged(null);
259             }
260 
261             updatePlaybackStatus();
262         }
263 
264         @Override
onSessionDestroyed()265         public void onSessionDestroyed() {
266             Log.w(TAG, "onSessionDestroyed");
267             onMediaControllerChanged(null);
268         }
269 
270         @Override
onMetadataChanged(@ullable MediaMetadataCompat mmdCompat)271         public void onMetadataChanged(@Nullable MediaMetadataCompat mmdCompat) {
272             // MediaSession#setMetadata builds an empty MediaMetadata when its argument is null,
273             // yet MediaMetadataCompat doesn't implement equals... so if the given mmdCompat's
274             // MediaMetadata equals EMPTY_MEDIA_METADATA, set mMediaMetadata to null to keep
275             // the code simpler everywhere else.
276             if ((mmdCompat != null) && EMPTY_MEDIA_METADATA.equals(mmdCompat.getMediaMetadata())) {
277                 mMediaMetadata = null;
278             } else {
279                 mMediaMetadata = mmdCompat;
280             }
281             MediaItemMetadata item =
282                     (mMediaMetadata != null) ? new MediaItemMetadata(mMediaMetadata) : null;
283             mMetadata.setValue(item);
284             updatePlaybackStatus();
285         }
286 
287         @Override
onQueueTitleChanged(CharSequence title)288         public void onQueueTitleChanged(CharSequence title) {
289             mQueueTitle.setValue(title);
290         }
291 
292         @Override
onQueueChanged(@ullable List<MediaSessionCompat.QueueItem> queue)293         public void onQueueChanged(@Nullable List<MediaSessionCompat.QueueItem> queue) {
294             List<MediaItemMetadata> filtered = queue == null ? Collections.emptyList()
295                     : queue.stream()
296                             .filter(item -> item.getDescription() != null
297                                     && item.getDescription().getTitle() != null)
298                             .map(MediaItemMetadata::new)
299                             .collect(Collectors.toList());
300 
301             mSanitizedQueue.setValue(filtered);
302             mHasQueue.setValue(!filtered.isEmpty());
303         }
304 
305         @Override
onPlaybackStateChanged(PlaybackStateCompat playbackState)306         public void onPlaybackStateChanged(PlaybackStateCompat playbackState) {
307             mPlaybackState = playbackState;
308             updatePlaybackStatus();
309         }
310 
updatePlaybackStatus()311         private void updatePlaybackStatus() {
312             if (mMediaController != null && mPlaybackState != null) {
313                 mPlaybackStateWrapper.setValue(
314                         new PlaybackStateWrapper(mMediaController, mMediaMetadata, mPlaybackState));
315             } else {
316                 mPlaybackStateWrapper.setValue(null);
317             }
318         }
319     }
320 
321     /** Convenient extension of {@link PlaybackStateCompat}. */
322     public static final class PlaybackStateWrapper {
323 
324         private final MediaControllerCompat mMediaController;
325         @Nullable
326         private final MediaMetadataCompat mMetadata;
327         private final PlaybackStateCompat mState;
328 
PlaybackStateWrapper(@onNull MediaControllerCompat mediaController, @Nullable MediaMetadataCompat metadata, @NonNull PlaybackStateCompat state)329         PlaybackStateWrapper(@NonNull MediaControllerCompat mediaController,
330                 @Nullable MediaMetadataCompat metadata, @NonNull PlaybackStateCompat state) {
331             mMediaController = mediaController;
332             mMetadata = metadata;
333             mState = state;
334         }
335 
336         /** Returns true if there's enough information in the state to show a UI for it. */
shouldDisplay()337         public boolean shouldDisplay() {
338             return (mMetadata != null) || (getMainAction() != ACTION_DISABLED);
339         }
340 
341         /** Returns the main action. */
342         @Action
getMainAction()343         public int getMainAction() {
344             @Actions long actions = mState.getActions();
345             @Action int stopAction = ACTION_DISABLED;
346             if ((actions & (PlaybackStateCompat.ACTION_PAUSE
347                     | PlaybackStateCompat.ACTION_PLAY_PAUSE)) != 0) {
348                 stopAction = ACTION_PAUSE;
349             } else if ((actions & PlaybackStateCompat.ACTION_STOP) != 0) {
350                 stopAction = ACTION_STOP;
351             }
352 
353             switch (mState.getState()) {
354                 case PlaybackStateCompat.STATE_PLAYING:
355                 case PlaybackStateCompat.STATE_BUFFERING:
356                 case PlaybackStateCompat.STATE_CONNECTING:
357                 case PlaybackStateCompat.STATE_FAST_FORWARDING:
358                 case PlaybackStateCompat.STATE_REWINDING:
359                 case PlaybackStateCompat.STATE_SKIPPING_TO_NEXT:
360                 case PlaybackStateCompat.STATE_SKIPPING_TO_PREVIOUS:
361                 case PlaybackStateCompat.STATE_SKIPPING_TO_QUEUE_ITEM:
362                     return stopAction;
363                 case PlaybackStateCompat.STATE_STOPPED:
364                 case PlaybackStateCompat.STATE_PAUSED:
365                 case PlaybackStateCompat.STATE_NONE:
366                 case PlaybackStateCompat.STATE_ERROR:
367                     return (actions & PlaybackStateCompat.ACTION_PLAY) != 0 ? ACTION_PLAY
368                             : ACTION_DISABLED;
369                 default:
370                     Log.w(TAG, String.format("Unknown PlaybackState: %d", mState.getState()));
371                     return ACTION_DISABLED;
372             }
373         }
374 
375         /**
376          * Returns the duration of the media item in milliseconds. The current position in this
377          * duration can be obtained by calling {@link #getProgress()}.
378          */
getMaxProgress()379         public long getMaxProgress() {
380             return mMetadata == null ? 0 :
381                     mMetadata.getLong(MediaMetadataCompat.METADATA_KEY_DURATION);
382         }
383 
384         /** Returns whether the current media source is playing a media item. */
isPlaying()385         public boolean isPlaying() {
386             return mState.getState() == PlaybackStateCompat.STATE_PLAYING;
387         }
388 
389         /** Returns whether the media source supports skipping to the next item. */
isSkipNextEnabled()390         public boolean isSkipNextEnabled() {
391             return (mState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0;
392         }
393 
394         /** Returns whether the media source supports skipping to the previous item. */
isSkipPreviousEnabled()395         public boolean isSkipPreviousEnabled() {
396             return (mState.getActions() & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0;
397         }
398 
399         /**
400          * Returns whether the media source supports seeking to a new location in the media stream.
401          */
isSeekToEnabled()402         public boolean isSeekToEnabled() {
403             return (mState.getActions() & PlaybackStateCompat.ACTION_SEEK_TO) != 0;
404         }
405 
406         /** Returns whether the media source requires reserved space for the skip to next action. */
isSkipNextReserved()407         public boolean isSkipNextReserved() {
408             return mMediaController.getExtras() != null
409                     && mMediaController.getExtras().getBoolean(
410                     MediaConstants.SLOT_RESERVATION_SKIP_TO_NEXT);
411         }
412 
413         /**
414          * Returns whether the media source requires reserved space for the skip to previous action.
415          */
iSkipPreviousReserved()416         public boolean iSkipPreviousReserved() {
417             return mMediaController.getExtras() != null
418                     && mMediaController.getExtras().getBoolean(
419                     MediaConstants.SLOT_RESERVATION_SKIP_TO_PREV);
420         }
421 
422         /** Returns whether the media source is loading (e.g.: buffering, connecting, etc.). */
isLoading()423         public boolean isLoading() {
424             int state = mState.getState();
425             return state == PlaybackStateCompat.STATE_BUFFERING
426                     || state == PlaybackStateCompat.STATE_CONNECTING
427                     || state == PlaybackStateCompat.STATE_FAST_FORWARDING
428                     || state == PlaybackStateCompat.STATE_REWINDING
429                     || state == PlaybackStateCompat.STATE_SKIPPING_TO_NEXT
430                     || state == PlaybackStateCompat.STATE_SKIPPING_TO_PREVIOUS
431                     || state == PlaybackStateCompat.STATE_SKIPPING_TO_QUEUE_ITEM;
432         }
433 
434         /** See {@link PlaybackStateCompat#getErrorMessage}. */
getErrorMessage()435         public CharSequence getErrorMessage() {
436             return mState.getErrorMessage();
437         }
438 
439         /** See {@link PlaybackStateCompat#getErrorCode()}. */
getErrorCode()440         public int getErrorCode() {
441             return mState.getErrorCode();
442         }
443 
444         /** See {@link PlaybackStateCompat#getActiveQueueItemId}. */
getActiveQueueItemId()445         public long getActiveQueueItemId() {
446             return mState.getActiveQueueItemId();
447         }
448 
449         /** See {@link PlaybackStateCompat#getState}. */
450         @PlaybackStateCompat.State
getState()451         public int getState() {
452             return mState.getState();
453         }
454 
455         /** See {@link PlaybackStateCompat#getExtras}. */
getExtras()456         public Bundle getExtras() {
457             return mState.getExtras();
458         }
459 
460         @VisibleForTesting
getStateCompat()461         PlaybackStateCompat getStateCompat() {
462             return mState;
463         }
464 
465         /**
466          * Returns a sorted list of custom actions available. Call {@link
467          * RawCustomPlaybackAction#fetchDrawable(Context)} to get the appropriate icon Drawable.
468          */
getCustomActions()469         public List<RawCustomPlaybackAction> getCustomActions() {
470             List<RawCustomPlaybackAction> actions = new ArrayList<>();
471             RawCustomPlaybackAction ratingAction = getRatingAction();
472             if (ratingAction != null) actions.add(ratingAction);
473 
474             for (PlaybackStateCompat.CustomAction action : mState.getCustomActions()) {
475                 String packageName = mMediaController.getPackageName();
476                 actions.add(
477                         new RawCustomPlaybackAction(action.getIcon(), packageName,
478                                 action.getAction(),
479                                 action.getExtras()));
480             }
481             return actions;
482         }
483 
484         @Nullable
getRatingAction()485         private RawCustomPlaybackAction getRatingAction() {
486             long stdActions = mState.getActions();
487             if ((stdActions & PlaybackStateCompat.ACTION_SET_RATING) == 0) return null;
488 
489             int ratingType = mMediaController.getRatingType();
490             if (ratingType != RatingCompat.RATING_HEART) return null;
491 
492             boolean hasHeart = false;
493             if (mMetadata != null) {
494                 RatingCompat rating = mMetadata.getRating(
495                         MediaMetadataCompat.METADATA_KEY_USER_RATING);
496                 hasHeart = rating != null && rating.hasHeart();
497             }
498 
499             int iconResource = hasHeart ? R.drawable.ic_star_filled : R.drawable.ic_star_empty;
500             Bundle extras = new Bundle();
501             extras.putBoolean(EXTRA_SET_HEART, !hasHeart);
502             return new RawCustomPlaybackAction(iconResource, null, ACTION_SET_RATING, extras);
503         }
504     }
505 
506 
507     /**
508      * Wraps the {@link android.media.session.MediaController.TransportControls TransportControls}
509      * for a {@link MediaControllerCompat} to send commands.
510      */
511     // TODO(arnaudberry) does this wrapping make sense since we're still null checking the wrapper?
512     // Should we call action methods on the model class instead ?
513     public class PlaybackController {
514         private final MediaControllerCompat mMediaController;
515 
PlaybackController(@ullable MediaControllerCompat mediaController)516         private PlaybackController(@Nullable MediaControllerCompat mediaController) {
517             mMediaController = mediaController;
518         }
519 
520         /**
521          * Sends a 'play' command to the media source
522          */
play()523         public void play() {
524             if (mMediaController != null) {
525                 mMediaController.getTransportControls().play();
526             }
527         }
528 
529         /**
530          * Sends a 'skip previews' command to the media source
531          */
skipToPrevious()532         public void skipToPrevious() {
533             if (mMediaController != null) {
534                 mMediaController.getTransportControls().skipToPrevious();
535             }
536         }
537 
538         /**
539          * Sends a 'skip next' command to the media source
540          */
skipToNext()541         public void skipToNext() {
542             if (mMediaController != null) {
543                 mMediaController.getTransportControls().skipToNext();
544             }
545         }
546 
547         /**
548          * Sends a 'pause' command to the media source
549          */
pause()550         public void pause() {
551             if (mMediaController != null) {
552                 mMediaController.getTransportControls().pause();
553             }
554         }
555 
556         /**
557          * Sends a 'stop' command to the media source
558          */
stop()559         public void stop() {
560             if (mMediaController != null) {
561                 mMediaController.getTransportControls().stop();
562             }
563         }
564 
565         /**
566          * Moves to a new location in the media stream
567          *
568          * @param pos Position to move to, in milliseconds.
569          */
seekTo(long pos)570         public void seekTo(long pos) {
571             if (mMediaController != null) {
572                 PlaybackStateCompat oldState = mMediaController.getPlaybackState();
573                 PlaybackStateCompat newState = new PlaybackStateCompat.Builder(oldState)
574                         .setState(oldState.getState(), pos, oldState.getPlaybackSpeed())
575                         .build();
576                 mMediaControllerCallback.onPlaybackStateChanged(newState);
577 
578                 mMediaController.getTransportControls().seekTo(pos);
579             }
580         }
581 
582         /**
583          * Sends a custom action to the media source
584          *
585          * @param action identifier of the custom action
586          * @param extras additional data to send to the media source.
587          */
doCustomAction(String action, Bundle extras)588         public void doCustomAction(String action, Bundle extras) {
589             if (mMediaController == null) return;
590             MediaControllerCompat.TransportControls cntrl = mMediaController.getTransportControls();
591 
592             if (ACTION_SET_RATING.equals(action)) {
593                 boolean setHeart = extras != null && extras.getBoolean(EXTRA_SET_HEART, false);
594                 cntrl.setRating(RatingCompat.newHeartRating(setHeart));
595             } else {
596                 cntrl.sendCustomAction(action, extras);
597             }
598         }
599 
600         /**
601          * Starts playing a given media item. This id corresponds to {@link
602          * MediaItemMetadata#getId()}.
603          */
playItem(String mediaItemId)604         public void playItem(String mediaItemId) {
605             if (mMediaController != null) {
606                 mMediaController.getTransportControls().playFromMediaId(mediaItemId, null);
607             }
608         }
609 
610         /**
611          * Skips to a particular item in the media queue. This id is {@link
612          * MediaItemMetadata#mQueueId} of the items obtained through {@link
613          * PlaybackViewModel#getQueue()}.
614          */
skipToQueueItem(long queueId)615         public void skipToQueueItem(long queueId) {
616             if (mMediaController != null) {
617                 mMediaController.getTransportControls().skipToQueueItem(queueId);
618             }
619         }
620 
621         /**
622          * Prepares the current media source for playback.
623          */
prepare()624         public void prepare() {
625             if (mMediaController != null) {
626                 mMediaController.getTransportControls().prepare();
627             }
628         }
629     }
630 
631     /**
632      * Abstract representation of a custom playback action. A custom playback action represents a
633      * visual element that can be used to trigger playback actions not included in the standard
634      * {@link PlaybackController} class. Custom actions for the current media source are exposed
635      * through {@link PlaybackStateWrapper#getCustomActions}
636      * <p>
637      * Does not contain a {@link Drawable} representation of the icon. Instances of this object
638      * should be converted to a {@link CustomPlaybackAction} via {@link
639      * RawCustomPlaybackAction#fetchDrawable(Context)} for display.
640      */
641     public static class RawCustomPlaybackAction {
642         // TODO (keyboardr): This class (and associtated translation code) will be merged with
643         // CustomPlaybackAction in a future CL.
644         /**
645          * Icon to display for this custom action
646          */
647         public final int mIcon;
648         /**
649          * If true, use the resources from the this package to resolve the icon. If null use our own
650          * resources.
651          */
652         @Nullable
653         public final String mPackageName;
654         /**
655          * Action identifier used to request this action to the media service
656          */
657         @NonNull
658         public final String mAction;
659         /**
660          * Any additional information to send along with the action identifier
661          */
662         @Nullable
663         public final Bundle mExtras;
664 
665         /**
666          * Creates a custom action
667          */
RawCustomPlaybackAction(int icon, String packageName, @NonNull String action, @Nullable Bundle extras)668         public RawCustomPlaybackAction(int icon, String packageName,
669                 @NonNull String action,
670                 @Nullable Bundle extras) {
671             mIcon = icon;
672             mPackageName = packageName;
673             mAction = action;
674             mExtras = extras;
675         }
676 
677         @Override
equals(Object o)678         public boolean equals(Object o) {
679             if (this == o) return true;
680             if (o == null || getClass() != o.getClass()) return false;
681 
682             RawCustomPlaybackAction that = (RawCustomPlaybackAction) o;
683 
684             return mIcon == that.mIcon
685                     && Objects.equals(mPackageName, that.mPackageName)
686                     && Objects.equals(mAction, that.mAction)
687                     && Objects.equals(mExtras, that.mExtras);
688         }
689 
690         @Override
hashCode()691         public int hashCode() {
692             return Objects.hash(mIcon, mPackageName, mAction, mExtras);
693         }
694 
695         /**
696          * Converts this {@link RawCustomPlaybackAction} into a {@link CustomPlaybackAction} by
697          * fetching the appropriate drawable for the icon.
698          *
699          * @param context Context into which the icon will be drawn
700          * @return the converted CustomPlaybackAction or null if appropriate {@link Resources}
701          * cannot be obtained
702          */
703         @Nullable
fetchDrawable(@onNull Context context)704         public CustomPlaybackAction fetchDrawable(@NonNull Context context) {
705             Drawable icon;
706             if (mPackageName == null) {
707                 icon = context.getDrawable(mIcon);
708             } else {
709                 Resources resources = getResourcesForPackage(context, mPackageName);
710                 if (resources == null) {
711                     return null;
712                 } else {
713                     // the resources may be from another package. we need to update the
714                     // configuration
715                     // using the context from the activity so we get the drawable from the
716                     // correct DPI
717                     // bucket.
718                     resources.updateConfiguration(context.getResources().getConfiguration(),
719                             context.getResources().getDisplayMetrics());
720                     icon = resources.getDrawable(mIcon, null);
721                 }
722             }
723             return new CustomPlaybackAction(icon, mAction, mExtras);
724         }
725 
getResourcesForPackage(Context context, String packageName)726         private Resources getResourcesForPackage(Context context, String packageName) {
727             try {
728                 return context.getPackageManager().getResourcesForApplication(packageName);
729             } catch (PackageManager.NameNotFoundException e) {
730                 Log.e(TAG, "Unable to get resources for " + packageName);
731                 return null;
732             }
733         }
734     }
735 
736 }
737