MediaSessionRecord.java revision 272e161c1a200900cb10b5b0cdab8ae1f123cabd
1/*
2 * Copyright (C) 2014 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
17package com.android.server.media;
18
19import android.app.PendingIntent;
20import android.content.ComponentName;
21import android.content.Context;
22import android.content.Intent;
23import android.content.pm.ParceledListSlice;
24import android.media.AudioManager;
25import android.media.AudioManagerInternal;
26import android.media.MediaDescription;
27import android.media.MediaMetadata;
28import android.media.Rating;
29import android.media.VolumeProvider;
30import android.media.session.ISession;
31import android.media.session.ISessionCallback;
32import android.media.session.ISessionController;
33import android.media.session.ISessionControllerCallback;
34import android.media.session.MediaController;
35import android.media.session.MediaController.PlaybackInfo;
36import android.media.session.MediaSession;
37import android.media.session.ParcelableVolumeInfo;
38import android.media.session.PlaybackState;
39import android.media.AudioAttributes;
40import android.net.Uri;
41import android.os.Binder;
42import android.os.Bundle;
43import android.os.DeadObjectException;
44import android.os.Handler;
45import android.os.IBinder;
46import android.os.Looper;
47import android.os.Message;
48import android.os.RemoteException;
49import android.os.ResultReceiver;
50import android.os.SystemClock;
51import android.util.Log;
52import android.util.Slog;
53import android.view.KeyEvent;
54
55import com.android.server.LocalServices;
56
57import java.io.PrintWriter;
58import java.util.ArrayList;
59import java.util.UUID;
60
61/**
62 * This is the system implementation of a Session. Apps will interact with the
63 * MediaSession wrapper class instead.
64 */
65public class MediaSessionRecord implements IBinder.DeathRecipient {
66    private static final String TAG = "MediaSessionRecord";
67    private static final boolean DEBUG = false;
68
69    /**
70     * The length of time a session will still be considered active after
71     * pausing in ms.
72     */
73    private static final int ACTIVE_BUFFER = 30000;
74
75    /**
76     * The amount of time we'll send an assumed volume after the last volume
77     * command before reverting to the last reported volume.
78     */
79    private static final int OPTIMISTIC_VOLUME_TIMEOUT = 1000;
80
81    private final MessageHandler mHandler;
82
83    private final int mOwnerPid;
84    private final int mOwnerUid;
85    private final int mUserId;
86    private final String mPackageName;
87    private final String mTag;
88    private final ControllerStub mController;
89    private final SessionStub mSession;
90    private final SessionCb mSessionCb;
91    private final MediaSessionService mService;
92
93    private final Object mLock = new Object();
94    private final ArrayList<ISessionControllerCallback> mControllerCallbacks =
95            new ArrayList<ISessionControllerCallback>();
96
97    private long mFlags;
98    private PendingIntent mMediaButtonReceiver;
99    private PendingIntent mLaunchIntent;
100
101    // TransportPerformer fields
102
103    private Bundle mExtras;
104    private MediaMetadata mMetadata;
105    private PlaybackState mPlaybackState;
106    private ParceledListSlice mQueue;
107    private CharSequence mQueueTitle;
108    private int mRatingType;
109    private long mLastActiveTime;
110    // End TransportPerformer fields
111
112    // Volume handling fields
113    private AudioAttributes mAudioAttrs;
114    private AudioManager mAudioManager;
115    private AudioManagerInternal mAudioManagerInternal;
116    private int mVolumeType = PlaybackInfo.PLAYBACK_TYPE_LOCAL;
117    private int mVolumeControlType = VolumeProvider.VOLUME_CONTROL_ABSOLUTE;
118    private int mMaxVolume = 0;
119    private int mCurrentVolume = 0;
120    private int mOptimisticVolume = -1;
121    // End volume handling fields
122
123    private boolean mIsActive = false;
124    private boolean mDestroyed = false;
125
126    public MediaSessionRecord(int ownerPid, int ownerUid, int userId, String ownerPackageName,
127            ISessionCallback cb, String tag, MediaSessionService service, Handler handler) {
128        mOwnerPid = ownerPid;
129        mOwnerUid = ownerUid;
130        mUserId = userId;
131        mPackageName = ownerPackageName;
132        mTag = tag;
133        mController = new ControllerStub();
134        mSession = new SessionStub();
135        mSessionCb = new SessionCb(cb);
136        mService = service;
137        mHandler = new MessageHandler(handler.getLooper());
138        mAudioManager = (AudioManager) service.getContext().getSystemService(Context.AUDIO_SERVICE);
139        mAudioManagerInternal = LocalServices.getService(AudioManagerInternal.class);
140        mAudioAttrs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).build();
141    }
142
143    /**
144     * Get the binder for the {@link MediaSession}.
145     *
146     * @return The session binder apps talk to.
147     */
148    public ISession getSessionBinder() {
149        return mSession;
150    }
151
152    /**
153     * Get the binder for the {@link MediaController}.
154     *
155     * @return The controller binder apps talk to.
156     */
157    public ISessionController getControllerBinder() {
158        return mController;
159    }
160
161    /**
162     * Get the info for this session.
163     *
164     * @return Info that identifies this session.
165     */
166    public String getPackageName() {
167        return mPackageName;
168    }
169
170    /**
171     * Get the tag for the session.
172     *
173     * @return The session's tag.
174     */
175    public String getTag() {
176        return mTag;
177    }
178
179    /**
180     * Get the intent the app set for their media button receiver.
181     *
182     * @return The pending intent set by the app or null.
183     */
184    public PendingIntent getMediaButtonReceiver() {
185        return mMediaButtonReceiver;
186    }
187
188    /**
189     * Get this session's flags.
190     *
191     * @return The flags for this session.
192     */
193    public long getFlags() {
194        return mFlags;
195    }
196
197    /**
198     * Check if this session has the specified flag.
199     *
200     * @param flag The flag to check.
201     * @return True if this session has that flag set, false otherwise.
202     */
203    public boolean hasFlag(int flag) {
204        return (mFlags & flag) != 0;
205    }
206
207    /**
208     * Get the user id this session was created for.
209     *
210     * @return The user id for this session.
211     */
212    public int getUserId() {
213        return mUserId;
214    }
215
216    /**
217     * Check if this session has system priorty and should receive media buttons
218     * before any other sessions.
219     *
220     * @return True if this is a system priority session, false otherwise
221     */
222    public boolean isSystemPriority() {
223        return (mFlags & MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY) != 0;
224    }
225
226    /**
227     * Send a volume adjustment to the session owner. Direction must be one of
228     * {@link AudioManager#ADJUST_LOWER}, {@link AudioManager#ADJUST_RAISE},
229     * {@link AudioManager#ADJUST_SAME}.
230     *
231     * @param direction The direction to adjust volume in.
232     * @param flags Any of the flags from {@link AudioManager}.
233     * @param packageName The package that made the original volume request.
234     * @param uid The uid that made the original volume request.
235     * @param useSuggested True to use adjustSuggestedStreamVolume instead of
236     *            adjustStreamVolume.
237     */
238    public void adjustVolume(int direction, int flags, String packageName, int uid,
239            boolean useSuggested) {
240        if (isPlaybackActive(false) || hasFlag(MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY)) {
241            flags &= ~AudioManager.FLAG_PLAY_SOUND;
242        }
243        if (direction > 1) {
244            direction = 1;
245        } else if (direction < -1) {
246            direction = -1;
247        }
248        if (mVolumeType == PlaybackInfo.PLAYBACK_TYPE_LOCAL) {
249            int stream = AudioAttributes.toLegacyStreamType(mAudioAttrs);
250            if (useSuggested) {
251                mAudioManagerInternal.adjustSuggestedStreamVolumeForUid(stream, direction, flags,
252                        packageName, uid);
253            } else {
254                mAudioManagerInternal.adjustStreamVolumeForUid(stream, direction, flags,
255                        packageName, uid);
256            }
257        } else {
258            if (mVolumeControlType == VolumeProvider.VOLUME_CONTROL_FIXED) {
259                // Nothing to do, the volume cannot be changed
260                return;
261            }
262            mSessionCb.adjustVolume(direction);
263
264            int volumeBefore = (mOptimisticVolume < 0 ? mCurrentVolume : mOptimisticVolume);
265            mOptimisticVolume = volumeBefore + direction;
266            mOptimisticVolume = Math.max(0, Math.min(mOptimisticVolume, mMaxVolume));
267            mHandler.removeCallbacks(mClearOptimisticVolumeRunnable);
268            mHandler.postDelayed(mClearOptimisticVolumeRunnable, OPTIMISTIC_VOLUME_TIMEOUT);
269            if (volumeBefore != mOptimisticVolume) {
270                pushVolumeUpdate();
271            }
272
273            if (DEBUG) {
274                Log.d(TAG, "Adjusted optimistic volume to " + mOptimisticVolume + " max is "
275                        + mMaxVolume);
276            }
277        }
278    }
279
280    public void setVolumeTo(int value, int flags, String packageName, int uid) {
281        if (mVolumeType == PlaybackInfo.PLAYBACK_TYPE_LOCAL) {
282            int stream = AudioAttributes.toLegacyStreamType(mAudioAttrs);
283            mAudioManagerInternal.setStreamVolumeForUid(stream, value, flags, packageName, uid);
284        } else {
285            if (mVolumeControlType != VolumeProvider.VOLUME_CONTROL_ABSOLUTE) {
286                // Nothing to do. The volume can't be set directly.
287                return;
288            }
289            value = Math.max(0, Math.min(value, mMaxVolume));
290            mSessionCb.setVolumeTo(value);
291
292            int volumeBefore = (mOptimisticVolume < 0 ? mCurrentVolume : mOptimisticVolume);
293            mOptimisticVolume = Math.max(0, Math.min(value, mMaxVolume));
294            mHandler.removeCallbacks(mClearOptimisticVolumeRunnable);
295            mHandler.postDelayed(mClearOptimisticVolumeRunnable, OPTIMISTIC_VOLUME_TIMEOUT);
296            if (volumeBefore != mOptimisticVolume) {
297                pushVolumeUpdate();
298            }
299
300            if (DEBUG) {
301                Log.d(TAG, "Set optimistic volume to " + mOptimisticVolume + " max is "
302                        + mMaxVolume);
303            }
304        }
305    }
306
307    /**
308     * Check if this session has been set to active by the app.
309     *
310     * @return True if the session is active, false otherwise.
311     */
312    public boolean isActive() {
313        return mIsActive && !mDestroyed;
314    }
315
316    /**
317     * Check if the session is currently performing playback. This will also
318     * return true if the session was recently paused.
319     *
320     * @param includeRecentlyActive True if playback that was recently paused
321     *            should count, false if it shouldn't.
322     * @return True if the session is performing playback, false otherwise.
323     */
324    public boolean isPlaybackActive(boolean includeRecentlyActive) {
325        int state = mPlaybackState == null ? 0 : mPlaybackState.getState();
326        if (MediaSession.isActiveState(state)) {
327            return true;
328        }
329        if (includeRecentlyActive && state == mPlaybackState.STATE_PAUSED) {
330            long inactiveTime = SystemClock.uptimeMillis() - mLastActiveTime;
331            if (inactiveTime < ACTIVE_BUFFER) {
332                return true;
333            }
334        }
335        return false;
336    }
337
338    /**
339     * Get the type of playback, either local or remote.
340     *
341     * @return The current type of playback.
342     */
343    public int getPlaybackType() {
344        return mVolumeType;
345    }
346
347    /**
348     * Get the local audio stream being used. Only valid if playback type is
349     * local.
350     *
351     * @return The audio stream the session is using.
352     */
353    public AudioAttributes getAudioAttributes() {
354        return mAudioAttrs;
355    }
356
357    /**
358     * Get the type of volume control. Only valid if playback type is remote.
359     *
360     * @return The volume control type being used.
361     */
362    public int getVolumeControl() {
363        return mVolumeControlType;
364    }
365
366    /**
367     * Get the max volume that can be set. Only valid if playback type is
368     * remote.
369     *
370     * @return The max volume that can be set.
371     */
372    public int getMaxVolume() {
373        return mMaxVolume;
374    }
375
376    /**
377     * Get the current volume for this session. Only valid if playback type is
378     * remote.
379     *
380     * @return The current volume of the remote playback.
381     */
382    public int getCurrentVolume() {
383        return mCurrentVolume;
384    }
385
386    /**
387     * Get the volume we'd like it to be set to. This is only valid for a short
388     * while after a call to adjust or set volume.
389     *
390     * @return The current optimistic volume or -1.
391     */
392    public int getOptimisticVolume() {
393        return mOptimisticVolume;
394    }
395
396    public boolean isTransportControlEnabled() {
397        return hasFlag(MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
398    }
399
400    @Override
401    public void binderDied() {
402        mService.sessionDied(this);
403    }
404
405    /**
406     * Finish cleaning up this session, including disconnecting if connected and
407     * removing the death observer from the callback binder.
408     */
409    public void onDestroy() {
410        synchronized (mLock) {
411            if (mDestroyed) {
412                return;
413            }
414            mDestroyed = true;
415            mHandler.post(MessageHandler.MSG_DESTROYED);
416        }
417    }
418
419    public ISessionCallback getCallback() {
420        return mSessionCb.mCb;
421    }
422
423    public void sendMediaButton(KeyEvent ke, int sequenceId, ResultReceiver cb) {
424        mSessionCb.sendMediaButton(ke, sequenceId, cb);
425    }
426
427    public void dump(PrintWriter pw, String prefix) {
428        pw.println(prefix + mTag + " " + this);
429
430        final String indent = prefix + "  ";
431        pw.println(indent + "ownerPid=" + mOwnerPid + ", ownerUid=" + mOwnerUid
432                + ", userId=" + mUserId);
433        pw.println(indent + "package=" + mPackageName);
434        pw.println(indent + "launchIntent=" + mLaunchIntent);
435        pw.println(indent + "mediaButtonReceiver=" + mMediaButtonReceiver);
436        pw.println(indent + "active=" + mIsActive);
437        pw.println(indent + "flags=" + mFlags);
438        pw.println(indent + "rating type=" + mRatingType);
439        pw.println(indent + "controllers: " + mControllerCallbacks.size());
440        pw.println(indent + "state=" + (mPlaybackState == null ? null : mPlaybackState.toString()));
441        pw.println(indent + "audioAttrs=" + mAudioAttrs);
442        pw.println(indent + "volumeType=" + mVolumeType + ", controlType=" + mVolumeControlType
443                + ", max=" + mMaxVolume + ", current=" + mCurrentVolume);
444        pw.println(indent + "metadata:" + getShortMetadataString());
445        pw.println(indent + "queueTitle=" + mQueueTitle + ", size="
446                + (mQueue == null ? 0 : mQueue.getList().size()));
447    }
448
449    @Override
450    public String toString() {
451        return mPackageName + "/" + mTag;
452    }
453
454    private String getShortMetadataString() {
455        int fields = mMetadata == null ? 0 : mMetadata.size();
456        MediaDescription description = mMetadata == null ? null : mMetadata
457                .getDescription();
458        return "size=" + fields + ", description=" + description;
459    }
460
461    private void pushPlaybackStateUpdate() {
462        synchronized (mLock) {
463            if (mDestroyed) {
464                return;
465            }
466            for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) {
467                ISessionControllerCallback cb = mControllerCallbacks.get(i);
468                try {
469                    cb.onPlaybackStateChanged(mPlaybackState);
470                } catch (DeadObjectException e) {
471                    mControllerCallbacks.remove(i);
472                    Log.w(TAG, "Removed dead callback in pushPlaybackStateUpdate.", e);
473                } catch (RemoteException e) {
474                    Log.w(TAG, "unexpected exception in pushPlaybackStateUpdate.", e);
475                }
476            }
477        }
478    }
479
480    private void pushMetadataUpdate() {
481        synchronized (mLock) {
482            if (mDestroyed) {
483                return;
484            }
485            for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) {
486                ISessionControllerCallback cb = mControllerCallbacks.get(i);
487                try {
488                    cb.onMetadataChanged(mMetadata);
489                } catch (DeadObjectException e) {
490                    Log.w(TAG, "Removing dead callback in pushMetadataUpdate. ", e);
491                    mControllerCallbacks.remove(i);
492                } catch (RemoteException e) {
493                    Log.w(TAG, "unexpected exception in pushMetadataUpdate. ", e);
494                }
495            }
496        }
497    }
498
499    private void pushQueueUpdate() {
500        synchronized (mLock) {
501            if (mDestroyed) {
502                return;
503            }
504            for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) {
505                ISessionControllerCallback cb = mControllerCallbacks.get(i);
506                try {
507                    cb.onQueueChanged(mQueue);
508                } catch (DeadObjectException e) {
509                    mControllerCallbacks.remove(i);
510                    Log.w(TAG, "Removed dead callback in pushQueueUpdate.", e);
511                } catch (RemoteException e) {
512                    Log.w(TAG, "unexpected exception in pushQueueUpdate.", e);
513                }
514            }
515        }
516    }
517
518    private void pushQueueTitleUpdate() {
519        synchronized (mLock) {
520            if (mDestroyed) {
521                return;
522            }
523            for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) {
524                ISessionControllerCallback cb = mControllerCallbacks.get(i);
525                try {
526                    cb.onQueueTitleChanged(mQueueTitle);
527                } catch (DeadObjectException e) {
528                    mControllerCallbacks.remove(i);
529                    Log.w(TAG, "Removed dead callback in pushQueueTitleUpdate.", e);
530                } catch (RemoteException e) {
531                    Log.w(TAG, "unexpected exception in pushQueueTitleUpdate.", e);
532                }
533            }
534        }
535    }
536
537    private void pushExtrasUpdate() {
538        synchronized (mLock) {
539            if (mDestroyed) {
540                return;
541            }
542            for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) {
543                ISessionControllerCallback cb = mControllerCallbacks.get(i);
544                try {
545                    cb.onExtrasChanged(mExtras);
546                } catch (DeadObjectException e) {
547                    mControllerCallbacks.remove(i);
548                    Log.w(TAG, "Removed dead callback in pushExtrasUpdate.", e);
549                } catch (RemoteException e) {
550                    Log.w(TAG, "unexpected exception in pushExtrasUpdate.", e);
551                }
552            }
553        }
554    }
555
556    private void pushVolumeUpdate() {
557        synchronized (mLock) {
558            if (mDestroyed) {
559                return;
560            }
561            ParcelableVolumeInfo info = mController.getVolumeAttributes();
562            for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) {
563                ISessionControllerCallback cb = mControllerCallbacks.get(i);
564                try {
565                    cb.onVolumeInfoChanged(info);
566                } catch (DeadObjectException e) {
567                    Log.w(TAG, "Removing dead callback in pushVolumeUpdate. ", e);
568                } catch (RemoteException e) {
569                    Log.w(TAG, "Unexpected exception in pushVolumeUpdate. ", e);
570                }
571            }
572        }
573    }
574
575    private void pushEvent(String event, Bundle data) {
576        synchronized (mLock) {
577            if (mDestroyed) {
578                return;
579            }
580            for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) {
581                ISessionControllerCallback cb = mControllerCallbacks.get(i);
582                try {
583                    cb.onEvent(event, data);
584                } catch (DeadObjectException e) {
585                    Log.w(TAG, "Removing dead callback in pushEvent.", e);
586                    mControllerCallbacks.remove(i);
587                } catch (RemoteException e) {
588                    Log.w(TAG, "unexpected exception in pushEvent.", e);
589                }
590            }
591        }
592    }
593
594    private void pushSessionDestroyed() {
595        synchronized (mLock) {
596            // This is the only method that may be (and can only be) called
597            // after the session is destroyed.
598            if (!mDestroyed) {
599                return;
600            }
601            for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) {
602                ISessionControllerCallback cb = mControllerCallbacks.get(i);
603                try {
604                    cb.onSessionDestroyed();
605                } catch (DeadObjectException e) {
606                    Log.w(TAG, "Removing dead callback in pushEvent.", e);
607                    mControllerCallbacks.remove(i);
608                } catch (RemoteException e) {
609                    Log.w(TAG, "unexpected exception in pushEvent.", e);
610                }
611            }
612            // After notifying clear all listeners
613            mControllerCallbacks.clear();
614        }
615    }
616
617    private PlaybackState getStateWithUpdatedPosition() {
618        PlaybackState state = mPlaybackState;
619        long duration = -1;
620        if (mMetadata != null && mMetadata.containsKey(MediaMetadata.METADATA_KEY_DURATION)) {
621            duration = mMetadata.getLong(MediaMetadata.METADATA_KEY_DURATION);
622        }
623        PlaybackState result = null;
624        if (state != null) {
625            if (state.getState() == PlaybackState.STATE_PLAYING
626                    || state.getState() == PlaybackState.STATE_FAST_FORWARDING
627                    || state.getState() == PlaybackState.STATE_REWINDING) {
628                long updateTime = state.getLastPositionUpdateTime();
629                long currentTime = SystemClock.elapsedRealtime();
630                if (updateTime > 0) {
631                    long position = (long) (state.getPlaybackSpeed()
632                            * (currentTime - updateTime)) + state.getPosition();
633                    if (duration >= 0 && position > duration) {
634                        position = duration;
635                    } else if (position < 0) {
636                        position = 0;
637                    }
638                    PlaybackState.Builder builder = new PlaybackState.Builder(state);
639                    builder.setState(state.getState(), position, state.getPlaybackSpeed(),
640                            currentTime);
641                    result = builder.build();
642                }
643            }
644        }
645        return result == null ? state : result;
646    }
647
648    private int getControllerCbIndexForCb(ISessionControllerCallback cb) {
649        IBinder binder = cb.asBinder();
650        for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) {
651            if (binder.equals(mControllerCallbacks.get(i).asBinder())) {
652                return i;
653            }
654        }
655        return -1;
656    }
657
658    private final Runnable mClearOptimisticVolumeRunnable = new Runnable() {
659        @Override
660        public void run() {
661            boolean needUpdate = (mOptimisticVolume != mCurrentVolume);
662            mOptimisticVolume = -1;
663            if (needUpdate) {
664                pushVolumeUpdate();
665            }
666        }
667    };
668
669    private final class SessionStub extends ISession.Stub {
670        @Override
671        public void destroy() {
672            mService.destroySession(MediaSessionRecord.this);
673        }
674
675        @Override
676        public void sendEvent(String event, Bundle data) {
677            mHandler.post(MessageHandler.MSG_SEND_EVENT, event, data);
678        }
679
680        @Override
681        public ISessionController getController() {
682            return mController;
683        }
684
685        @Override
686        public void setActive(boolean active) {
687            mIsActive = active;
688            mService.updateSession(MediaSessionRecord.this);
689            mHandler.post(MessageHandler.MSG_UPDATE_SESSION_STATE);
690        }
691
692        @Override
693        public void setFlags(int flags) {
694            if ((flags & MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY) != 0) {
695                int pid = getCallingPid();
696                int uid = getCallingUid();
697                mService.enforcePhoneStatePermission(pid, uid);
698            }
699            mFlags = flags;
700            mHandler.post(MessageHandler.MSG_UPDATE_SESSION_STATE);
701        }
702
703        @Override
704        public void setMediaButtonReceiver(PendingIntent pi) {
705            mMediaButtonReceiver = pi;
706        }
707
708        @Override
709        public void setLaunchPendingIntent(PendingIntent pi) {
710            mLaunchIntent = pi;
711        }
712
713        @Override
714        public void setMetadata(MediaMetadata metadata) {
715            mMetadata = metadata;
716            mHandler.post(MessageHandler.MSG_UPDATE_METADATA);
717        }
718
719        @Override
720        public void setPlaybackState(PlaybackState state) {
721            int oldState = mPlaybackState == null ? 0 : mPlaybackState.getState();
722            int newState = state == null ? 0 : state.getState();
723            if (MediaSession.isActiveState(oldState) && newState == PlaybackState.STATE_PAUSED) {
724                mLastActiveTime = SystemClock.elapsedRealtime();
725            }
726            mPlaybackState = state;
727            mService.onSessionPlaystateChange(MediaSessionRecord.this, oldState, newState);
728            mHandler.post(MessageHandler.MSG_UPDATE_PLAYBACK_STATE);
729        }
730
731        @Override
732        public void setQueue(ParceledListSlice queue) {
733            mQueue = queue;
734            mHandler.post(MessageHandler.MSG_UPDATE_QUEUE);
735        }
736
737        @Override
738        public void setQueueTitle(CharSequence title) {
739            mQueueTitle = title;
740            mHandler.post(MessageHandler.MSG_UPDATE_QUEUE_TITLE);
741        }
742
743        @Override
744        public void setExtras(Bundle extras) {
745            mExtras = extras;
746            mHandler.post(MessageHandler.MSG_UPDATE_EXTRAS);
747        }
748
749        @Override
750        public void setRatingType(int type) {
751            mRatingType = type;
752        }
753
754        @Override
755        public void setCurrentVolume(int volume) {
756            mCurrentVolume = volume;
757            mHandler.post(MessageHandler.MSG_UPDATE_VOLUME);
758        }
759
760        @Override
761        public void setPlaybackToLocal(AudioAttributes attributes) {
762            boolean typeChanged;
763            synchronized (mLock) {
764                typeChanged = mVolumeType == PlaybackInfo.PLAYBACK_TYPE_REMOTE;
765                mVolumeType = PlaybackInfo.PLAYBACK_TYPE_LOCAL;
766                if (attributes != null) {
767                    mAudioAttrs = attributes;
768                } else {
769                    Log.e(TAG, "Received null audio attributes, using existing attributes");
770                }
771            }
772            if (typeChanged) {
773                mService.onSessionPlaybackTypeChanged(MediaSessionRecord.this);
774            }
775        }
776
777        @Override
778        public void setPlaybackToRemote(int control, int max) {
779            boolean typeChanged;
780            synchronized (mLock) {
781                typeChanged = mVolumeType == PlaybackInfo.PLAYBACK_TYPE_LOCAL;
782                mVolumeType = PlaybackInfo.PLAYBACK_TYPE_REMOTE;
783                mVolumeControlType = control;
784                mMaxVolume = max;
785            }
786            if (typeChanged) {
787                mService.onSessionPlaybackTypeChanged(MediaSessionRecord.this);
788            }
789        }
790    }
791
792    class SessionCb {
793        private final ISessionCallback mCb;
794
795        public SessionCb(ISessionCallback cb) {
796            mCb = cb;
797        }
798
799        public boolean sendMediaButton(KeyEvent keyEvent, int sequenceId, ResultReceiver cb) {
800            Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
801            mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
802            try {
803                mCb.onMediaButton(mediaButtonIntent, sequenceId, cb);
804                return true;
805            } catch (RemoteException e) {
806                Slog.e(TAG, "Remote failure in sendMediaRequest.", e);
807            }
808            return false;
809        }
810
811        public void sendCommand(String command, Bundle args, ResultReceiver cb) {
812            try {
813                mCb.onCommand(command, args, cb);
814            } catch (RemoteException e) {
815                Slog.e(TAG, "Remote failure in sendCommand.", e);
816            }
817        }
818
819        public void sendCustomAction(String action, Bundle args) {
820            try {
821                mCb.onCustomAction(action, args);
822            } catch (RemoteException e) {
823                Slog.e(TAG, "Remote failure in sendCustomAction.", e);
824            }
825        }
826
827        public void play() {
828            try {
829                mCb.onPlay();
830            } catch (RemoteException e) {
831                Slog.e(TAG, "Remote failure in play.", e);
832            }
833        }
834
835        public void playFromMediaId(String mediaId, Bundle extras) {
836            try {
837                mCb.onPlayFromMediaId(mediaId, extras);
838            } catch (RemoteException e) {
839                Slog.e(TAG, "Remote failure in playUri.", e);
840            }
841        }
842
843        public void playFromSearch(String query, Bundle extras) {
844            try {
845                mCb.onPlayFromSearch(query, extras);
846            } catch (RemoteException e) {
847                Slog.e(TAG, "Remote failure in playFromSearch.", e);
848            }
849        }
850
851        public void skipToTrack(long id) {
852            try {
853                mCb.onSkipToTrack(id);
854            } catch (RemoteException e) {
855                Slog.e(TAG, "Remote failure in skipToTrack", e);
856            }
857        }
858
859        public void pause() {
860            try {
861                mCb.onPause();
862            } catch (RemoteException e) {
863                Slog.e(TAG, "Remote failure in pause.", e);
864            }
865        }
866
867        public void stop() {
868            try {
869                mCb.onStop();
870            } catch (RemoteException e) {
871                Slog.e(TAG, "Remote failure in stop.", e);
872            }
873        }
874
875        public void next() {
876            try {
877                mCb.onNext();
878            } catch (RemoteException e) {
879                Slog.e(TAG, "Remote failure in next.", e);
880            }
881        }
882
883        public void previous() {
884            try {
885                mCb.onPrevious();
886            } catch (RemoteException e) {
887                Slog.e(TAG, "Remote failure in previous.", e);
888            }
889        }
890
891        public void fastForward() {
892            try {
893                mCb.onFastForward();
894            } catch (RemoteException e) {
895                Slog.e(TAG, "Remote failure in fastForward.", e);
896            }
897        }
898
899        public void rewind() {
900            try {
901                mCb.onRewind();
902            } catch (RemoteException e) {
903                Slog.e(TAG, "Remote failure in rewind.", e);
904            }
905        }
906
907        public void seekTo(long pos) {
908            try {
909                mCb.onSeekTo(pos);
910            } catch (RemoteException e) {
911                Slog.e(TAG, "Remote failure in seekTo.", e);
912            }
913        }
914
915        public void rate(Rating rating) {
916            try {
917                mCb.onRate(rating);
918            } catch (RemoteException e) {
919                Slog.e(TAG, "Remote failure in rate.", e);
920            }
921        }
922
923        public void adjustVolume(int direction) {
924            try {
925                mCb.onAdjustVolume(direction);
926            } catch (RemoteException e) {
927                Slog.e(TAG, "Remote failure in adjustVolume.", e);
928            }
929        }
930
931        public void setVolumeTo(int value) {
932            try {
933                mCb.onSetVolumeTo(value);
934            } catch (RemoteException e) {
935                Slog.e(TAG, "Remote failure in setVolumeTo.", e);
936            }
937        }
938    }
939
940    class ControllerStub extends ISessionController.Stub {
941        @Override
942        public void sendCommand(String command, Bundle args, ResultReceiver cb)
943                throws RemoteException {
944            mSessionCb.sendCommand(command, args, cb);
945        }
946
947        @Override
948        public boolean sendMediaButton(KeyEvent mediaButtonIntent) {
949            return mSessionCb.sendMediaButton(mediaButtonIntent, 0, null);
950        }
951
952        @Override
953        public void registerCallbackListener(ISessionControllerCallback cb) {
954            synchronized (mLock) {
955                // If this session is already destroyed tell the caller and
956                // don't add them.
957                if (mDestroyed) {
958                    try {
959                        cb.onSessionDestroyed();
960                    } catch (Exception e) {
961                        // ignored
962                    }
963                    return;
964                }
965                if (getControllerCbIndexForCb(cb) < 0) {
966                    mControllerCallbacks.add(cb);
967                    if (DEBUG) {
968                        Log.d(TAG, "registering controller callback " + cb);
969                    }
970                }
971            }
972        }
973
974        @Override
975        public void unregisterCallbackListener(ISessionControllerCallback cb)
976                throws RemoteException {
977            synchronized (mLock) {
978                int index = getControllerCbIndexForCb(cb);
979                if (index != -1) {
980                    mControllerCallbacks.remove(index);
981                }
982                if (DEBUG) {
983                    Log.d(TAG, "unregistering callback " + cb + ". index=" + index);
984                }
985            }
986        }
987
988        @Override
989        public String getPackageName() {
990            return mPackageName;
991        }
992
993        @Override
994        public String getTag() {
995            return mTag;
996        }
997
998        @Override
999        public PendingIntent getLaunchPendingIntent() {
1000            return mLaunchIntent;
1001        }
1002
1003        @Override
1004        public long getFlags() {
1005            return mFlags;
1006        }
1007
1008        @Override
1009        public ParcelableVolumeInfo getVolumeAttributes() {
1010            synchronized (mLock) {
1011                int type;
1012                int max;
1013                int current;
1014                if (mVolumeType == PlaybackInfo.PLAYBACK_TYPE_REMOTE) {
1015                    type = mVolumeControlType;
1016                    max = mMaxVolume;
1017                    current = mOptimisticVolume != -1 ? mOptimisticVolume
1018                            : mCurrentVolume;
1019                } else {
1020                    int stream = AudioAttributes.toLegacyStreamType(mAudioAttrs);
1021                    type = VolumeProvider.VOLUME_CONTROL_ABSOLUTE;
1022                    max = mAudioManager.getStreamMaxVolume(stream);
1023                    current = mAudioManager.getStreamVolume(stream);
1024                }
1025                return new ParcelableVolumeInfo(mVolumeType, mAudioAttrs, type, max, current);
1026            }
1027        }
1028
1029        @Override
1030        public void adjustVolume(int direction, int flags, String packageName) {
1031            int uid = Binder.getCallingUid();
1032            final long token = Binder.clearCallingIdentity();
1033            try {
1034                MediaSessionRecord.this.adjustVolume(direction, flags, packageName, uid, false);
1035            } finally {
1036                Binder.restoreCallingIdentity(token);
1037            }
1038        }
1039
1040        @Override
1041        public void setVolumeTo(int value, int flags, String packageName) {
1042            int uid = Binder.getCallingUid();
1043            final long token = Binder.clearCallingIdentity();
1044            try {
1045                MediaSessionRecord.this.setVolumeTo(value, flags, packageName, uid);
1046            } finally {
1047                Binder.restoreCallingIdentity(token);
1048            }
1049        }
1050
1051        @Override
1052        public void play() throws RemoteException {
1053            mSessionCb.play();
1054        }
1055
1056        @Override
1057        public void playFromMediaId(String mediaId, Bundle extras) throws RemoteException {
1058            mSessionCb.playFromMediaId(mediaId, extras);
1059        }
1060
1061        @Override
1062        public void playFromSearch(String query, Bundle extras) throws RemoteException {
1063            mSessionCb.playFromSearch(query, extras);
1064        }
1065
1066        @Override
1067        public void skipToQueueItem(long id) {
1068            mSessionCb.skipToTrack(id);
1069        }
1070
1071
1072        @Override
1073        public void pause() throws RemoteException {
1074            mSessionCb.pause();
1075        }
1076
1077        @Override
1078        public void stop() throws RemoteException {
1079            mSessionCb.stop();
1080        }
1081
1082        @Override
1083        public void next() throws RemoteException {
1084            mSessionCb.next();
1085        }
1086
1087        @Override
1088        public void previous() throws RemoteException {
1089            mSessionCb.previous();
1090        }
1091
1092        @Override
1093        public void fastForward() throws RemoteException {
1094            mSessionCb.fastForward();
1095        }
1096
1097        @Override
1098        public void rewind() throws RemoteException {
1099            mSessionCb.rewind();
1100        }
1101
1102        @Override
1103        public void seekTo(long pos) throws RemoteException {
1104            mSessionCb.seekTo(pos);
1105        }
1106
1107        @Override
1108        public void rate(Rating rating) throws RemoteException {
1109            mSessionCb.rate(rating);
1110        }
1111
1112        @Override
1113        public void sendCustomAction(String action, Bundle args)
1114                throws RemoteException {
1115            mSessionCb.sendCustomAction(action, args);
1116        }
1117
1118
1119        @Override
1120        public MediaMetadata getMetadata() {
1121            return mMetadata;
1122        }
1123
1124        @Override
1125        public PlaybackState getPlaybackState() {
1126            return getStateWithUpdatedPosition();
1127        }
1128
1129        @Override
1130        public ParceledListSlice getQueue() {
1131            return mQueue;
1132        }
1133
1134        @Override
1135        public CharSequence getQueueTitle() {
1136            return mQueueTitle;
1137        }
1138
1139        @Override
1140        public Bundle getExtras() {
1141            return mExtras;
1142        }
1143
1144        @Override
1145        public int getRatingType() {
1146            return mRatingType;
1147        }
1148
1149        @Override
1150        public boolean isTransportControlEnabled() {
1151            return MediaSessionRecord.this.isTransportControlEnabled();
1152        }
1153    }
1154
1155    private class MessageHandler extends Handler {
1156        private static final int MSG_UPDATE_METADATA = 1;
1157        private static final int MSG_UPDATE_PLAYBACK_STATE = 2;
1158        private static final int MSG_UPDATE_QUEUE = 3;
1159        private static final int MSG_UPDATE_QUEUE_TITLE = 4;
1160        private static final int MSG_UPDATE_EXTRAS = 5;
1161        private static final int MSG_SEND_EVENT = 6;
1162        private static final int MSG_UPDATE_SESSION_STATE = 7;
1163        private static final int MSG_UPDATE_VOLUME = 8;
1164        private static final int MSG_DESTROYED = 9;
1165
1166        public MessageHandler(Looper looper) {
1167            super(looper);
1168        }
1169        @Override
1170        public void handleMessage(Message msg) {
1171            switch (msg.what) {
1172                case MSG_UPDATE_METADATA:
1173                    pushMetadataUpdate();
1174                    break;
1175                case MSG_UPDATE_PLAYBACK_STATE:
1176                    pushPlaybackStateUpdate();
1177                    break;
1178                case MSG_UPDATE_QUEUE:
1179                    pushQueueUpdate();
1180                    break;
1181                case MSG_UPDATE_QUEUE_TITLE:
1182                    pushQueueTitleUpdate();
1183                    break;
1184                case MSG_UPDATE_EXTRAS:
1185                    pushExtrasUpdate();
1186                    break;
1187                case MSG_SEND_EVENT:
1188                    pushEvent((String) msg.obj, msg.getData());
1189                    break;
1190                case MSG_UPDATE_SESSION_STATE:
1191                    // TODO add session state
1192                    break;
1193                case MSG_UPDATE_VOLUME:
1194                    pushVolumeUpdate();
1195                    break;
1196                case MSG_DESTROYED:
1197                    pushSessionDestroyed();
1198            }
1199        }
1200
1201        public void post(int what) {
1202            post(what, null);
1203        }
1204
1205        public void post(int what, Object obj) {
1206            obtainMessage(what, obj).sendToTarget();
1207        }
1208
1209        public void post(int what, Object obj, Bundle data) {
1210            Message msg = obtainMessage(what, obj);
1211            msg.setData(data);
1212            msg.sendToTarget();
1213        }
1214    }
1215
1216}
1217