MediaSessionRecord.java revision 4646d288821d62fdfe481be67d8b7fed7d7eabd8
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.ActivityManager;
20import android.content.Intent;
21import android.content.pm.PackageManager;
22import android.media.routeprovider.RouteRequest;
23import android.media.session.ISessionController;
24import android.media.session.ISessionControllerCallback;
25import android.media.session.ISession;
26import android.media.session.ISessionCallback;
27import android.media.session.SessionController;
28import android.media.session.MediaMetadata;
29import android.media.session.RouteCommand;
30import android.media.session.RouteInfo;
31import android.media.session.RouteOptions;
32import android.media.session.RouteEvent;
33import android.media.session.Session;
34import android.media.session.SessionInfo;
35import android.media.session.RouteInterface;
36import android.media.session.PlaybackState;
37import android.media.Rating;
38import android.os.Bundle;
39import android.os.Handler;
40import android.os.IBinder;
41import android.os.Looper;
42import android.os.Message;
43import android.os.RemoteException;
44import android.os.ResultReceiver;
45import android.os.SystemClock;
46import android.os.UserHandle;
47import android.text.TextUtils;
48import android.util.Log;
49import android.util.Pair;
50import android.util.Slog;
51import android.view.KeyEvent;
52
53import java.io.PrintWriter;
54import java.util.ArrayList;
55import java.util.List;
56import java.util.UUID;
57
58/**
59 * This is the system implementation of a Session. Apps will interact with the
60 * MediaSession wrapper class instead.
61 */
62public class MediaSessionRecord implements IBinder.DeathRecipient {
63    private static final String TAG = "MediaSessionRecord";
64
65    /**
66     * These are the playback states that count as currently active.
67     */
68    private static final int[] ACTIVE_STATES = {
69            PlaybackState.PLAYSTATE_FAST_FORWARDING,
70            PlaybackState.PLAYSTATE_REWINDING,
71            PlaybackState.PLAYSTATE_SKIPPING_BACKWARDS,
72            PlaybackState.PLAYSTATE_SKIPPING_FORWARDS,
73            PlaybackState.PLAYSTATE_BUFFERING,
74            PlaybackState.PLAYSTATE_CONNECTING,
75            PlaybackState.PLAYSTATE_PLAYING };
76
77    /**
78     * The length of time a session will still be considered active after
79     * pausing in ms.
80     */
81    private static final int ACTIVE_BUFFER = 30000;
82
83    private final MessageHandler mHandler;
84
85    private final int mOwnerPid;
86    private final int mOwnerUid;
87    private final int mUserId;
88    private final SessionInfo mSessionInfo;
89    private final String mTag;
90    private final ControllerStub mController;
91    private final SessionStub mSession;
92    private final SessionCb mSessionCb;
93    private final MediaSessionService mService;
94
95    private final Object mLock = new Object();
96    private final ArrayList<ISessionControllerCallback> mControllerCallbacks =
97            new ArrayList<ISessionControllerCallback>();
98    private final ArrayList<RouteRequest> mRequests = new ArrayList<RouteRequest>();
99
100    private RouteInfo mRoute;
101    private RouteOptions mRequest;
102    private RouteConnectionRecord mConnection;
103    // TODO define a RouteState class with relevant info
104    private int mRouteState;
105    private long mFlags;
106
107    // TransportPerformer fields
108
109    private MediaMetadata mMetadata;
110    private PlaybackState mPlaybackState;
111    private int mRatingType;
112    private long mLastActiveTime;
113    // End TransportPerformer fields
114
115    private boolean mIsActive = false;
116    private boolean mDestroyed = false;
117
118    public MediaSessionRecord(int ownerPid, int ownerUid, int userId, String ownerPackageName,
119            ISessionCallback cb, String tag, MediaSessionService service, Handler handler) {
120        mOwnerPid = ownerPid;
121        mOwnerUid = ownerUid;
122        mUserId = userId;
123        mSessionInfo = new SessionInfo(UUID.randomUUID().toString(), ownerPackageName);
124        mTag = tag;
125        mController = new ControllerStub();
126        mSession = new SessionStub();
127        mSessionCb = new SessionCb(cb);
128        mService = service;
129        mHandler = new MessageHandler(handler.getLooper());
130    }
131
132    /**
133     * Get the binder for the {@link Session}.
134     *
135     * @return The session binder apps talk to.
136     */
137    public ISession getSessionBinder() {
138        return mSession;
139    }
140
141    /**
142     * Get the binder for the {@link SessionController}.
143     *
144     * @return The controller binder apps talk to.
145     */
146    public ISessionController getControllerBinder() {
147        return mController;
148    }
149
150    /**
151     * Get the set of route requests this session is interested in.
152     *
153     * @return The list of RouteRequests
154     */
155    public List<RouteRequest> getRouteRequests() {
156        return mRequests;
157    }
158
159    /**
160     * Get the route this session is currently on.
161     *
162     * @return The route the session is on.
163     */
164    public RouteInfo getRoute() {
165        return mRoute;
166    }
167
168    /**
169     * Get the info for this session.
170     *
171     * @return Info that identifies this session.
172     */
173    public SessionInfo getSessionInfo() {
174        return mSessionInfo;
175    }
176
177    /**
178     * Get this session's flags.
179     *
180     * @return The flags for this session.
181     */
182    public long getFlags() {
183        return mFlags;
184    }
185
186    /**
187     * Check if this session has the specified flag.
188     *
189     * @param flag The flag to check.
190     * @return True if this session has that flag set, false otherwise.
191     */
192    public boolean hasFlag(int flag) {
193        return (mFlags & flag) != 0;
194    }
195
196    /**
197     * Get the user id this session was created for.
198     *
199     * @return The user id for this session.
200     */
201    public int getUserId() {
202        return mUserId;
203    }
204
205    /**
206     * Check if this session has system priorty and should receive media buttons
207     * before any other sessions.
208     *
209     * @return True if this is a system priority session, false otherwise
210     */
211    public boolean isSystemPriority() {
212        return (mFlags & Session.FLAG_EXCLUSIVE_GLOBAL_PRIORITY) != 0;
213    }
214
215    /**
216     * Set the selected route. This does not connect to the route, just notifies
217     * the app that a new route has been selected.
218     *
219     * @param route The route that was selected.
220     */
221    public void selectRoute(RouteInfo route) {
222        synchronized (mLock) {
223            if (route != mRoute) {
224                disconnect(Session.DISCONNECT_REASON_ROUTE_CHANGED);
225            }
226            mRoute = route;
227        }
228        mSessionCb.sendRouteChange(route);
229    }
230
231    /**
232     * Update the state of the route this session is using and notify the
233     * session.
234     *
235     * @param state The new state of the route.
236     */
237    public void setRouteState(int state) {
238        mSessionCb.sendRouteStateChange(state);
239    }
240
241    /**
242     * Send an event to this session from the route it is using.
243     *
244     * @param event The event to send.
245     */
246    public void sendRouteEvent(RouteEvent event) {
247        mSessionCb.sendRouteEvent(event);
248    }
249
250    /**
251     * Set the connection to use for the selected route and notify the app it is
252     * now connected.
253     *
254     * @param route The route the connection is to.
255     * @param request The request that was used to connect.
256     * @param connection The connection to the route.
257     * @return True if this connection is still valid, false if it is stale.
258     */
259    public boolean setRouteConnected(RouteInfo route, RouteOptions request,
260            RouteConnectionRecord connection) {
261        synchronized (mLock) {
262            if (mDestroyed) {
263                Log.i(TAG, "setRouteConnected: session has been destroyed");
264                connection.disconnect();
265                return false;
266            }
267            if (mRoute == null || !TextUtils.equals(route.getId(), mRoute.getId())) {
268                Log.w(TAG, "setRouteConnected: connected route is stale");
269                connection.disconnect();
270                return false;
271            }
272            if (request != mRequest) {
273                Log.w(TAG, "setRouteConnected: connection request is stale");
274                connection.disconnect();
275                return false;
276            }
277            mConnection = connection;
278            mConnection.setListener(mConnectionListener);
279            mSessionCb.sendRouteConnected();
280        }
281        return true;
282    }
283
284    /**
285     * Check if this session has been set to active by the app.
286     *
287     * @return True if the session is active, false otherwise.
288     */
289    public boolean isActive() {
290        return mIsActive && !mDestroyed;
291    }
292
293    /**
294     * Check if the session is currently performing playback. This will also
295     * return true if the session was recently paused.
296     *
297     * @return True if the session is performing playback, false otherwise.
298     */
299    public boolean isPlaybackActive() {
300        int state = mPlaybackState == null ? 0 : mPlaybackState.getState();
301        if (isActiveState(state)) {
302            return true;
303        }
304        if (state == mPlaybackState.PLAYSTATE_PAUSED) {
305            long inactiveTime = SystemClock.uptimeMillis() - mLastActiveTime;
306            if (inactiveTime < ACTIVE_BUFFER) {
307                return true;
308            }
309        }
310        return false;
311    }
312
313    /**
314     * @return True if this session is currently connected to a route.
315     */
316    public boolean isConnected() {
317        return mConnection != null;
318    }
319
320    public void disconnect(int reason) {
321        synchronized (mLock) {
322            if (!mDestroyed) {
323                disconnectLocked(reason);
324            }
325        }
326    }
327
328    private void disconnectLocked(int reason) {
329        if (mConnection != null) {
330            mConnection.setListener(null);
331            mConnection.disconnect();
332            mConnection = null;
333            pushDisconnected(reason);
334        }
335    }
336
337    public boolean isTransportControlEnabled() {
338        return hasFlag(Session.FLAG_HANDLES_TRANSPORT_CONTROLS);
339    }
340
341    @Override
342    public void binderDied() {
343        mService.sessionDied(this);
344    }
345
346    /**
347     * Finish cleaning up this session, including disconnecting if connected and
348     * removing the death observer from the callback binder.
349     */
350    public void onDestroy() {
351        synchronized (mLock) {
352            if (mDestroyed) {
353                return;
354            }
355            if (isConnected()) {
356                disconnectLocked(Session.DISCONNECT_REASON_SESSION_DESTROYED);
357            }
358            mRoute = null;
359            mRequest = null;
360            mDestroyed = true;
361        }
362    }
363
364    public ISessionCallback getCallback() {
365        return mSessionCb.mCb;
366    }
367
368    public void dump(PrintWriter pw, String prefix) {
369        pw.println(prefix + mTag + " " + this);
370
371        final String indent = prefix + "  ";
372        pw.println(indent + "ownerPid=" + mOwnerPid + ", ownerUid=" + mOwnerUid
373                + ", userId=" + mUserId);
374        pw.println(indent + "info=" + mSessionInfo.toString());
375        pw.println(indent + "active=" + mIsActive);
376        pw.println(indent + "flags=" + mFlags);
377        pw.println(indent + "rating type=" + mRatingType);
378        pw.println(indent + "controllers: " + mControllerCallbacks.size());
379        pw.println(indent + "state=" + (mPlaybackState == null ? null : mPlaybackState.toString()));
380        pw.println(indent + "metadata:" + getShortMetadataString());
381        pw.println(indent + "route requests {");
382        int size = mRequests.size();
383        for (int i = 0; i < size; i++) {
384            pw.println(indent + "  " + mRequests.get(i).toString());
385        }
386        pw.println(indent + "}");
387        pw.println(indent + "route=" + (mRoute == null ? null : mRoute.toString()));
388        pw.println(indent + "connection=" + (mConnection == null ? null : mConnection.toString()));
389        pw.println(indent + "params=" + (mRequest == null ? null : mRequest.toString()));
390    }
391
392    private boolean isActiveState(int state) {
393        for (int i = 0; i < ACTIVE_STATES.length; i++) {
394            if (ACTIVE_STATES[i] == state) {
395                return true;
396            }
397        }
398        return false;
399    }
400
401    private String getShortMetadataString() {
402        int fields = mMetadata == null ? 0 : mMetadata.size();
403        String title = mMetadata == null ? null : mMetadata
404                .getString(MediaMetadata.METADATA_KEY_TITLE);
405        return "size=" + fields + ", title=" + title;
406    }
407
408    private void pushDisconnected(int reason) {
409        synchronized (mLock) {
410            mSessionCb.sendRouteDisconnected(reason);
411        }
412    }
413
414    private void pushPlaybackStateUpdate() {
415        synchronized (mLock) {
416            if (mDestroyed) {
417                return;
418            }
419            for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) {
420                ISessionControllerCallback cb = mControllerCallbacks.get(i);
421                try {
422                    cb.onPlaybackStateChanged(mPlaybackState);
423                } catch (RemoteException e) {
424                    Log.w(TAG, "Removing dead callback in pushPlaybackStateUpdate.", e);
425                    mControllerCallbacks.remove(i);
426                }
427            }
428        }
429    }
430
431    private void pushMetadataUpdate() {
432        synchronized (mLock) {
433            if (mDestroyed) {
434                return;
435            }
436            for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) {
437                ISessionControllerCallback cb = mControllerCallbacks.get(i);
438                try {
439                    cb.onMetadataChanged(mMetadata);
440                } catch (RemoteException e) {
441                    Log.w(TAG, "Removing dead callback in pushMetadataUpdate.", e);
442                    mControllerCallbacks.remove(i);
443                }
444            }
445        }
446    }
447
448    private void pushRouteUpdate() {
449        synchronized (mLock) {
450            if (mDestroyed) {
451                return;
452            }
453            for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) {
454                ISessionControllerCallback cb = mControllerCallbacks.get(i);
455                try {
456                    cb.onRouteChanged(mRoute);
457                } catch (RemoteException e) {
458                    Log.w(TAG, "Removing dead callback in pushRouteUpdate.", e);
459                    mControllerCallbacks.remove(i);
460                }
461            }
462        }
463    }
464
465    private void pushEvent(String event, Bundle data) {
466        synchronized (mLock) {
467            if (mDestroyed) {
468                return;
469            }
470            for (int i = mControllerCallbacks.size() - 1; i >= 0; i--) {
471                ISessionControllerCallback cb = mControllerCallbacks.get(i);
472                try {
473                    cb.onEvent(event, data);
474                } catch (RemoteException e) {
475                    Log.w(TAG, "Error with callback in pushEvent.", e);
476                }
477            }
478        }
479    }
480
481    private void pushRouteCommand(RouteCommand command, ResultReceiver cb) {
482        synchronized (mLock) {
483            if (mDestroyed) {
484                return;
485            }
486            if (mRoute == null || !TextUtils.equals(command.getRouteInfo(), mRoute.getId())) {
487                if (cb != null) {
488                    cb.send(RouteInterface.RESULT_ROUTE_IS_STALE, null);
489                    return;
490                }
491            }
492            if (mConnection != null) {
493                mConnection.sendCommand(command, cb);
494            } else if (cb != null) {
495                cb.send(RouteInterface.RESULT_NOT_CONNECTED, null);
496            }
497        }
498    }
499
500    private PlaybackState getStateWithUpdatedPosition() {
501        PlaybackState state = mPlaybackState;
502        long duration = -1;
503        if (mMetadata != null && mMetadata.containsKey(MediaMetadata.METADATA_KEY_DURATION)) {
504            duration = mMetadata.getLong(MediaMetadata.METADATA_KEY_DURATION);
505        }
506        PlaybackState result = null;
507        if (state != null) {
508            if (state.getState() == PlaybackState.PLAYSTATE_PLAYING
509                    || state.getState() == PlaybackState.PLAYSTATE_FAST_FORWARDING
510                    || state.getState() == PlaybackState.PLAYSTATE_REWINDING) {
511                long updateTime = state.getLastPositionUpdateTime();
512                if (updateTime > 0) {
513                    long position = (long) (state.getRate()
514                            * (SystemClock.elapsedRealtime() - updateTime)) + state.getPosition();
515                    if (duration >= 0 && position > duration) {
516                        position = duration;
517                    } else if (position < 0) {
518                        position = 0;
519                    }
520                    result = new PlaybackState(state);
521                    result.setState(state.getState(), position, state.getRate());
522                }
523            }
524        }
525        return result == null ? state : result;
526    }
527
528    private final RouteConnectionRecord.Listener mConnectionListener
529            = new RouteConnectionRecord.Listener() {
530        @Override
531        public void onEvent(RouteEvent event) {
532            RouteEvent eventForSession = new RouteEvent(null, event.getIface(),
533                    event.getEvent(), event.getExtras());
534            mSessionCb.sendRouteEvent(eventForSession);
535        }
536
537        @Override
538        public void disconnect() {
539            MediaSessionRecord.this.disconnect(Session.DISCONNECT_REASON_PROVIDER_DISCONNECTED);
540        }
541    };
542
543    private final class SessionStub extends ISession.Stub {
544        @Override
545        public void destroy() {
546            mService.destroySession(MediaSessionRecord.this);
547        }
548
549        @Override
550        public void sendEvent(String event, Bundle data) {
551            mHandler.post(MessageHandler.MSG_SEND_EVENT, event, data);
552        }
553
554        @Override
555        public ISessionController getController() {
556            return mController;
557        }
558
559        @Override
560        public void setActive(boolean active) {
561            mIsActive = active;
562            mService.updateSession(MediaSessionRecord.this);
563            mHandler.post(MessageHandler.MSG_UPDATE_SESSION_STATE);
564        }
565
566        @Override
567        public void setFlags(int flags) {
568            if ((flags & Session.FLAG_EXCLUSIVE_GLOBAL_PRIORITY) != 0) {
569                int pid = getCallingPid();
570                int uid = getCallingUid();
571                mService.enforcePhoneStatePermission(pid, uid);
572            }
573            mFlags = flags;
574            mHandler.post(MessageHandler.MSG_UPDATE_SESSION_STATE);
575        }
576
577        @Override
578        public void setMetadata(MediaMetadata metadata) {
579            mMetadata = metadata;
580            mHandler.post(MessageHandler.MSG_UPDATE_METADATA);
581        }
582
583        @Override
584        public void setPlaybackState(PlaybackState state) {
585            int oldState = mPlaybackState == null ? 0 : mPlaybackState.getState();
586            int newState = state == null ? 0 : state.getState();
587            if (isActiveState(oldState) && newState == PlaybackState.PLAYSTATE_PAUSED) {
588                mLastActiveTime = SystemClock.elapsedRealtime();
589            }
590            mPlaybackState = state;
591            mService.onSessionPlaystateChange(MediaSessionRecord.this, oldState, newState);
592            mHandler.post(MessageHandler.MSG_UPDATE_PLAYBACK_STATE);
593        }
594
595        @Override
596        public void setRatingType(int type) {
597            mRatingType = type;
598        }
599
600        @Override
601        public void sendRouteCommand(RouteCommand command, ResultReceiver cb) {
602            mHandler.post(MessageHandler.MSG_SEND_COMMAND,
603                    new Pair<RouteCommand, ResultReceiver>(command, cb));
604        }
605
606        @Override
607        public boolean setRoute(RouteInfo route) throws RemoteException {
608            // TODO decide if allowed to set route and if the route exists
609            return false;
610        }
611
612        @Override
613        public void connectToRoute(RouteInfo route, RouteOptions request)
614                throws RemoteException {
615            if (mRoute == null || !TextUtils.equals(route.getId(), mRoute.getId())) {
616                throw new RemoteException("RouteInfo does not match current route");
617            }
618            mService.connectToRoute(MediaSessionRecord.this, route, request);
619            mRequest = request;
620        }
621
622        @Override
623        public void disconnectFromRoute(RouteInfo route) {
624            if (route != null && mRoute != null
625                    && TextUtils.equals(route.getId(), mRoute.getId())) {
626                disconnect(Session.DISCONNECT_REASON_SESSION_DISCONNECTED);
627            }
628        }
629
630        @Override
631        public void setRouteOptions(List<RouteOptions> options) throws RemoteException {
632            mRequests.clear();
633            for (int i = options.size() - 1; i >= 0; i--) {
634                RouteRequest request = new RouteRequest(mSessionInfo, options.get(i),
635                        false);
636                mRequests.add(request);
637            }
638        }
639    }
640
641    class SessionCb {
642        private final ISessionCallback mCb;
643
644        public SessionCb(ISessionCallback cb) {
645            mCb = cb;
646        }
647
648        public void sendMediaButton(KeyEvent keyEvent) {
649            Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
650            mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
651            try {
652                mCb.onMediaButton(mediaButtonIntent);
653            } catch (RemoteException e) {
654                Slog.e(TAG, "Remote failure in sendMediaRequest.", e);
655            }
656        }
657
658        public void sendCommand(String command, Bundle extras, ResultReceiver cb) {
659            try {
660                mCb.onCommand(command, extras, cb);
661            } catch (RemoteException e) {
662                Slog.e(TAG, "Remote failure in sendCommand.", e);
663            }
664        }
665
666        public void sendRouteChange(RouteInfo route) {
667            try {
668                mCb.onRequestRouteChange(route);
669            } catch (RemoteException e) {
670                Slog.e(TAG, "Remote failure in sendRouteChange.", e);
671            }
672        }
673
674        public void sendRouteStateChange(int state) {
675            try {
676                mCb.onRouteStateChange(state);
677            } catch (RemoteException e) {
678                Slog.e(TAG, "Remote failure in sendRouteStateChange.", e);
679            }
680        }
681
682        public void sendRouteEvent(RouteEvent event) {
683            try {
684                mCb.onRouteEvent(event);
685            } catch (RemoteException e) {
686                Slog.e(TAG, "Remote failure in sendRouteEvent.", e);
687            }
688        }
689
690        public void sendRouteConnected() {
691            try {
692                mCb.onRouteConnected(mRoute, mRequest);
693            } catch (RemoteException e) {
694                Slog.e(TAG, "Remote failure in sendRouteStateChange.", e);
695            }
696        }
697
698        public void sendRouteDisconnected(int reason) {
699            try {
700                mCb.onRouteDisconnected(mRoute, reason);
701            } catch (RemoteException e) {
702                Slog.e(TAG, "Remote failure in sendRouteDisconnected");
703            }
704        }
705
706        public void play() {
707            try {
708                mCb.onPlay();
709            } catch (RemoteException e) {
710                Slog.e(TAG, "Remote failure in play.", e);
711            }
712        }
713
714        public void pause() {
715            try {
716                mCb.onPause();
717            } catch (RemoteException e) {
718                Slog.e(TAG, "Remote failure in pause.", e);
719            }
720        }
721
722        public void stop() {
723            try {
724                mCb.onStop();
725            } catch (RemoteException e) {
726                Slog.e(TAG, "Remote failure in stop.", e);
727            }
728        }
729
730        public void next() {
731            try {
732                mCb.onNext();
733            } catch (RemoteException e) {
734                Slog.e(TAG, "Remote failure in next.", e);
735            }
736        }
737
738        public void previous() {
739            try {
740                mCb.onPrevious();
741            } catch (RemoteException e) {
742                Slog.e(TAG, "Remote failure in previous.", e);
743            }
744        }
745
746        public void fastForward() {
747            try {
748                mCb.onFastForward();
749            } catch (RemoteException e) {
750                Slog.e(TAG, "Remote failure in fastForward.", e);
751            }
752        }
753
754        public void rewind() {
755            try {
756                mCb.onRewind();
757            } catch (RemoteException e) {
758                Slog.e(TAG, "Remote failure in rewind.", e);
759            }
760        }
761
762        public void seekTo(long pos) {
763            try {
764                mCb.onSeekTo(pos);
765            } catch (RemoteException e) {
766                Slog.e(TAG, "Remote failure in seekTo.", e);
767            }
768        }
769
770        public void rate(Rating rating) {
771            try {
772                mCb.onRate(rating);
773            } catch (RemoteException e) {
774                Slog.e(TAG, "Remote failure in rate.", e);
775            }
776        }
777    }
778
779    class ControllerStub extends ISessionController.Stub {
780        @Override
781        public void sendCommand(String command, Bundle extras, ResultReceiver cb)
782                throws RemoteException {
783            mSessionCb.sendCommand(command, extras, cb);
784        }
785
786        @Override
787        public void sendMediaButton(KeyEvent mediaButtonIntent) {
788            mSessionCb.sendMediaButton(mediaButtonIntent);
789        }
790
791        @Override
792        public void registerCallbackListener(ISessionControllerCallback cb) {
793            synchronized (mLock) {
794                if (!mControllerCallbacks.contains(cb)) {
795                    mControllerCallbacks.add(cb);
796                }
797            }
798        }
799
800        @Override
801        public void unregisterCallbackListener(ISessionControllerCallback cb)
802                throws RemoteException {
803            synchronized (mLock) {
804                mControllerCallbacks.remove(cb);
805            }
806        }
807
808        @Override
809        public void play() throws RemoteException {
810            mSessionCb.play();
811        }
812
813        @Override
814        public void pause() throws RemoteException {
815            mSessionCb.pause();
816        }
817
818        @Override
819        public void stop() throws RemoteException {
820            mSessionCb.stop();
821        }
822
823        @Override
824        public void next() throws RemoteException {
825            mSessionCb.next();
826        }
827
828        @Override
829        public void previous() throws RemoteException {
830            mSessionCb.previous();
831        }
832
833        @Override
834        public void fastForward() throws RemoteException {
835            mSessionCb.fastForward();
836        }
837
838        @Override
839        public void rewind() throws RemoteException {
840            mSessionCb.rewind();
841        }
842
843        @Override
844        public void seekTo(long pos) throws RemoteException {
845            mSessionCb.seekTo(pos);
846        }
847
848        @Override
849        public void rate(Rating rating) throws RemoteException {
850            mSessionCb.rate(rating);
851        }
852
853
854        @Override
855        public MediaMetadata getMetadata() {
856            return mMetadata;
857        }
858
859        @Override
860        public PlaybackState getPlaybackState() {
861            return getStateWithUpdatedPosition();
862        }
863
864        @Override
865        public int getRatingType() {
866            return mRatingType;
867        }
868
869        @Override
870        public boolean isTransportControlEnabled() {
871            return MediaSessionRecord.this.isTransportControlEnabled();
872        }
873
874        @Override
875        public void showRoutePicker() {
876            mService.showRoutePickerForSession(MediaSessionRecord.this);
877        }
878    }
879
880    private class MessageHandler extends Handler {
881        private static final int MSG_UPDATE_METADATA = 1;
882        private static final int MSG_UPDATE_PLAYBACK_STATE = 2;
883        private static final int MSG_UPDATE_ROUTE = 3;
884        private static final int MSG_SEND_EVENT = 4;
885        private static final int MSG_UPDATE_ROUTE_FILTERS = 5;
886        private static final int MSG_SEND_COMMAND = 6;
887        private static final int MSG_UPDATE_SESSION_STATE = 7;
888
889        public MessageHandler(Looper looper) {
890            super(looper);
891        }
892        @Override
893        public void handleMessage(Message msg) {
894            switch (msg.what) {
895                case MSG_UPDATE_METADATA:
896                    pushMetadataUpdate();
897                    break;
898                case MSG_UPDATE_PLAYBACK_STATE:
899                    pushPlaybackStateUpdate();
900                    break;
901                case MSG_UPDATE_ROUTE:
902                    pushRouteUpdate();
903                    break;
904                case MSG_SEND_EVENT:
905                    pushEvent((String) msg.obj, msg.getData());
906                    break;
907                case MSG_SEND_COMMAND:
908                    Pair<RouteCommand, ResultReceiver> cmd =
909                            (Pair<RouteCommand, ResultReceiver>) msg.obj;
910                    pushRouteCommand(cmd.first, cmd.second);
911                    break;
912                case MSG_UPDATE_SESSION_STATE:
913                    // TODO add session state
914                    break;
915            }
916        }
917
918        public void post(int what) {
919            post(what, null);
920        }
921
922        public void post(int what, Object obj) {
923            obtainMessage(what, obj).sendToTarget();
924        }
925
926        public void post(int what, Object obj, Bundle data) {
927            Message msg = obtainMessage(what, obj);
928            msg.setData(data);
929            msg.sendToTarget();
930        }
931    }
932
933}
934