TvInputManagerService.java revision 8e6b51b0fb810ac990c863cc0579e2b2700ab7d6
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.tv;
18
19import static android.media.tv.TvInputManager.INPUT_STATE_CONNECTED;
20import static android.media.tv.TvInputManager.INPUT_STATE_DISCONNECTED;
21
22import android.app.ActivityManager;
23import android.content.BroadcastReceiver;
24import android.content.ComponentName;
25import android.content.ContentProviderOperation;
26import android.content.ContentProviderResult;
27import android.content.ContentResolver;
28import android.content.ContentUris;
29import android.content.ContentValues;
30import android.content.Context;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.OperationApplicationException;
34import android.content.ServiceConnection;
35import android.content.pm.PackageManager;
36import android.content.pm.ResolveInfo;
37import android.content.pm.ServiceInfo;
38import android.database.Cursor;
39import android.graphics.Rect;
40import android.hardware.hdmi.HdmiCecDeviceInfo;
41import android.media.tv.ITvInputClient;
42import android.media.tv.ITvInputHardware;
43import android.media.tv.ITvInputHardwareCallback;
44import android.media.tv.ITvInputManager;
45import android.media.tv.ITvInputManagerCallback;
46import android.media.tv.ITvInputService;
47import android.media.tv.ITvInputServiceCallback;
48import android.media.tv.ITvInputSession;
49import android.media.tv.ITvInputSessionCallback;
50import android.media.tv.TvContract;
51import android.media.tv.TvInputHardwareInfo;
52import android.media.tv.TvInputInfo;
53import android.media.tv.TvInputService;
54import android.media.tv.TvTrackInfo;
55import android.net.Uri;
56import android.os.Binder;
57import android.os.Bundle;
58import android.os.Handler;
59import android.os.IBinder;
60import android.os.Looper;
61import android.os.Message;
62import android.os.Process;
63import android.os.RemoteException;
64import android.os.UserHandle;
65import android.util.Slog;
66import android.util.SparseArray;
67import android.view.InputChannel;
68import android.view.Surface;
69
70import com.android.internal.content.PackageMonitor;
71import com.android.internal.os.SomeArgs;
72import com.android.internal.util.IndentingPrintWriter;
73import com.android.server.IoThread;
74import com.android.server.SystemService;
75
76import org.xmlpull.v1.XmlPullParserException;
77
78import java.io.FileDescriptor;
79import java.io.IOException;
80import java.io.PrintWriter;
81import java.util.ArrayList;
82import java.util.HashMap;
83import java.util.HashSet;
84import java.util.Iterator;
85import java.util.List;
86import java.util.Map;
87import java.util.Set;
88
89/** This class provides a system service that manages television inputs. */
90public final class TvInputManagerService extends SystemService {
91    // STOPSHIP: Turn debugging off.
92    private static final boolean DEBUG = true;
93    private static final String TAG = "TvInputManagerService";
94
95    private final Context mContext;
96    private final TvInputHardwareManager mTvInputHardwareManager;
97
98    private final ContentResolver mContentResolver;
99
100    // A global lock.
101    private final Object mLock = new Object();
102
103    // ID of the current user.
104    private int mCurrentUserId = UserHandle.USER_OWNER;
105
106    // A map from user id to UserState.
107    private final SparseArray<UserState> mUserStates = new SparseArray<UserState>();
108
109    private final Handler mLogHandler;
110
111    public TvInputManagerService(Context context) {
112        super(context);
113
114        mContext = context;
115        mContentResolver = context.getContentResolver();
116        mLogHandler = new LogHandler(IoThread.get().getLooper());
117
118        mTvInputHardwareManager = new TvInputHardwareManager(context, new HardwareListener());
119
120        synchronized (mLock) {
121            mUserStates.put(mCurrentUserId, new UserState());
122        }
123    }
124
125    @Override
126    public void onStart() {
127        publishBinderService(Context.TV_INPUT_SERVICE, new BinderService());
128    }
129
130    @Override
131    public void onBootPhase(int phase) {
132        if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
133            registerBroadcastReceivers();
134        } else if (phase == SystemService.PHASE_THIRD_PARTY_APPS_CAN_START) {
135            synchronized (mLock) {
136                buildTvInputListLocked(mCurrentUserId);
137            }
138        }
139        mTvInputHardwareManager.onBootPhase(phase);
140    }
141
142    private void registerBroadcastReceivers() {
143        PackageMonitor monitor = new PackageMonitor() {
144            @Override
145            public void onSomePackagesChanged() {
146                synchronized (mLock) {
147                    buildTvInputListLocked(mCurrentUserId);
148                }
149            }
150
151            @Override
152            public void onPackageRemoved(String packageName, int uid) {
153                synchronized (mLock) {
154                    UserState userState = getUserStateLocked(mCurrentUserId);
155                    if (!userState.packageSet.contains(packageName)) {
156                        // Not a TV input package.
157                        return;
158                    }
159                }
160
161                ArrayList<ContentProviderOperation> operations =
162                        new ArrayList<ContentProviderOperation>();
163
164                String selection = TvContract.BaseTvColumns.COLUMN_PACKAGE_NAME + "=?";
165                String[] selectionArgs = { packageName };
166
167                operations.add(ContentProviderOperation.newDelete(TvContract.Channels.CONTENT_URI)
168                        .withSelection(selection, selectionArgs).build());
169                operations.add(ContentProviderOperation.newDelete(TvContract.Programs.CONTENT_URI)
170                        .withSelection(selection, selectionArgs).build());
171                operations.add(ContentProviderOperation
172                        .newDelete(TvContract.WatchedPrograms.CONTENT_URI)
173                        .withSelection(selection, selectionArgs).build());
174
175                ContentProviderResult[] results = null;
176                try {
177                    results = mContentResolver.applyBatch(TvContract.AUTHORITY, operations);
178                } catch (RemoteException | OperationApplicationException e) {
179                    Slog.e(TAG, "error in applyBatch" + e);
180                }
181
182                if (DEBUG) {
183                    Slog.d(TAG, "onPackageRemoved(packageName=" + packageName + ", uid=" + uid
184                            + ")");
185                    Slog.d(TAG, "results=" + results);
186                }
187            }
188        };
189        monitor.register(mContext, null, UserHandle.ALL, true);
190
191        IntentFilter intentFilter = new IntentFilter();
192        intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
193        intentFilter.addAction(Intent.ACTION_USER_REMOVED);
194        mContext.registerReceiverAsUser(new BroadcastReceiver() {
195            @Override
196            public void onReceive(Context context, Intent intent) {
197                String action = intent.getAction();
198                if (Intent.ACTION_USER_SWITCHED.equals(action)) {
199                    switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
200                } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
201                    removeUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
202                }
203            }
204        }, UserHandle.ALL, intentFilter, null, null);
205    }
206
207    private static boolean hasHardwarePermission(PackageManager pm, ComponentName name) {
208        return pm.checkPermission(android.Manifest.permission.TV_INPUT_HARDWARE,
209                name.getPackageName()) == PackageManager.PERMISSION_GRANTED;
210    }
211
212    private void buildTvInputListLocked(int userId) {
213        UserState userState = getUserStateLocked(userId);
214
215        Map<String, TvInputState> inputMap = new HashMap<String, TvInputState>();
216        userState.packageSet.clear();
217
218        if (DEBUG) Slog.d(TAG, "buildTvInputList");
219        PackageManager pm = mContext.getPackageManager();
220        List<ResolveInfo> services = pm.queryIntentServices(
221                new Intent(TvInputService.SERVICE_INTERFACE),
222                PackageManager.GET_SERVICES | PackageManager.GET_META_DATA);
223        List<TvInputInfo> infoList = new ArrayList<TvInputInfo>();
224        for (ResolveInfo ri : services) {
225            ServiceInfo si = ri.serviceInfo;
226            if (!android.Manifest.permission.BIND_TV_INPUT.equals(si.permission)) {
227                Slog.w(TAG, "Skipping TV input " + si.name + ": it does not require the permission "
228                        + android.Manifest.permission.BIND_TV_INPUT);
229                continue;
230            }
231            try {
232                infoList.clear();
233                ComponentName service = new ComponentName(si.packageName, si.name);
234                if (hasHardwarePermission(pm, service)) {
235                    ServiceState serviceState = userState.serviceStateMap.get(service);
236                    if (serviceState == null) {
237                        // We see this hardware TV input service for the first time; we need to
238                        // prepare the ServiceState object so that we can connect to the service and
239                        // let it add TvInputInfo objects to mInputList if there's any.
240                        serviceState = new ServiceState(service, userId);
241                        userState.serviceStateMap.put(service, serviceState);
242                    } else {
243                        infoList.addAll(serviceState.mInputList);
244                    }
245                } else {
246                    infoList.add(TvInputInfo.createTvInputInfo(mContext, ri));
247                }
248
249                for (TvInputInfo info : infoList) {
250                    if (DEBUG) Slog.d(TAG, "add " + info.getId());
251                    TvInputState state = userState.inputMap.get(info.getId());
252                    if (state == null) {
253                        state = new TvInputState();
254                    }
255                    state.mInfo = info;
256                    inputMap.put(info.getId(), state);
257                }
258
259                // Reconnect the service if existing input is updated.
260                updateServiceConnectionLocked(service, userId);
261
262                userState.packageSet.add(si.packageName);
263            } catch (IOException | XmlPullParserException e) {
264                Slog.e(TAG, "Can't load TV input " + si.name, e);
265            }
266        }
267
268        for (String inputId : inputMap.keySet()) {
269            if (!userState.inputMap.containsKey(inputId)) {
270                notifyInputAddedLocked(userState, inputId);
271            }
272        }
273
274        for (String inputId : userState.inputMap.keySet()) {
275            if (!inputMap.containsKey(inputId)) {
276                notifyInputRemovedLocked(userState, inputId);
277            }
278        }
279
280        userState.inputMap.clear();
281        userState.inputMap = inputMap;
282    }
283
284    private void switchUser(int userId) {
285        synchronized (mLock) {
286            if (mCurrentUserId == userId) {
287                return;
288            }
289            // final int oldUserId = mCurrentUserId;
290            // TODO: Release services and sessions in the old user state, if needed.
291            mCurrentUserId = userId;
292
293            UserState userState = mUserStates.get(userId);
294            if (userState == null) {
295                userState = new UserState();
296            }
297            mUserStates.put(userId, userState);
298            buildTvInputListLocked(userId);
299        }
300    }
301
302    private void removeUser(int userId) {
303        synchronized (mLock) {
304            UserState userState = mUserStates.get(userId);
305            if (userState == null) {
306                return;
307            }
308            // Release created sessions.
309            for (SessionState state : userState.sessionStateMap.values()) {
310                if (state.mSession != null) {
311                    try {
312                        state.mSession.release();
313                    } catch (RemoteException e) {
314                        Slog.e(TAG, "error in release", e);
315                    }
316                }
317            }
318            userState.sessionStateMap.clear();
319
320            // Unregister all callbacks and unbind all services.
321            for (ServiceState serviceState : userState.serviceStateMap.values()) {
322                if (serviceState.mCallback != null) {
323                    try {
324                        serviceState.mService.unregisterCallback(serviceState.mCallback);
325                    } catch (RemoteException e) {
326                        Slog.e(TAG, "error in unregisterCallback", e);
327                    }
328                }
329                serviceState.mClientTokens.clear();
330                mContext.unbindService(serviceState.mConnection);
331            }
332            userState.serviceStateMap.clear();
333
334            userState.clientStateMap.clear();
335
336            mUserStates.remove(userId);
337        }
338    }
339
340    private UserState getUserStateLocked(int userId) {
341        UserState userState = mUserStates.get(userId);
342        if (userState == null) {
343            throw new IllegalStateException("User state not found for user ID " + userId);
344        }
345        return userState;
346    }
347
348    private ServiceState getServiceStateLocked(ComponentName name, int userId) {
349        UserState userState = getUserStateLocked(userId);
350        ServiceState serviceState = userState.serviceStateMap.get(name);
351        if (serviceState == null) {
352            throw new IllegalStateException("Service state not found for " + name + " (userId="
353                    + userId + ")");
354        }
355        return serviceState;
356    }
357
358    private SessionState getSessionStateLocked(IBinder sessionToken, int callingUid, int userId) {
359        UserState userState = getUserStateLocked(userId);
360        SessionState sessionState = userState.sessionStateMap.get(sessionToken);
361        if (sessionState == null) {
362            throw new IllegalArgumentException("Session state not found for token " + sessionToken);
363        }
364        // Only the application that requested this session or the system can access it.
365        if (callingUid != Process.SYSTEM_UID && callingUid != sessionState.mCallingUid) {
366            throw new SecurityException("Illegal access to the session with token " + sessionToken
367                    + " from uid " + callingUid);
368        }
369        return sessionState;
370    }
371
372    private ITvInputSession getSessionLocked(IBinder sessionToken, int callingUid, int userId) {
373        SessionState sessionState = getSessionStateLocked(sessionToken, callingUid, userId);
374        ITvInputSession session = sessionState.mSession;
375        if (session == null) {
376            throw new IllegalStateException("Session not yet created for token " + sessionToken);
377        }
378        return session;
379    }
380
381    private int resolveCallingUserId(int callingPid, int callingUid, int requestedUserId,
382            String methodName) {
383        return ActivityManager.handleIncomingUser(callingPid, callingUid, requestedUserId, false,
384                false, methodName, null);
385    }
386
387    private static boolean shouldMaintainConnection(ServiceState serviceState) {
388        return !serviceState.mClientTokens.isEmpty()
389                || !serviceState.mSessionTokens.isEmpty()
390                || serviceState.mIsHardware;
391        // TODO: Find a way to maintain connection only when necessary.
392    }
393
394    private void updateServiceConnectionLocked(ComponentName service, int userId) {
395        UserState userState = getUserStateLocked(userId);
396        ServiceState serviceState = userState.serviceStateMap.get(service);
397        if (serviceState == null) {
398            return;
399        }
400        if (serviceState.mReconnecting) {
401            if (!serviceState.mSessionTokens.isEmpty()) {
402                // wait until all the sessions are removed.
403                return;
404            }
405            serviceState.mReconnecting = false;
406        }
407        boolean maintainConnection = shouldMaintainConnection(serviceState);
408        if (serviceState.mService == null && maintainConnection && userId == mCurrentUserId) {
409            // This means that the service is not yet connected but its state indicates that we
410            // have pending requests. Then, connect the service.
411            if (serviceState.mBound) {
412                // We have already bound to the service so we don't try to bind again until after we
413                // unbind later on.
414                return;
415            }
416            if (DEBUG) {
417                Slog.d(TAG, "bindServiceAsUser(service=" + service + ", userId=" + userId + ")");
418            }
419
420            Intent i = new Intent(TvInputService.SERVICE_INTERFACE).setComponent(service);
421            // Binding service may fail if the service is updating.
422            // In that case, the connection will be revived in buildTvInputListLocked called by
423            // onSomePackagesChanged.
424            serviceState.mBound = mContext.bindServiceAsUser(
425                    i, serviceState.mConnection, Context.BIND_AUTO_CREATE, new UserHandle(userId));
426        } else if (serviceState.mService != null && !maintainConnection) {
427            // This means that the service is already connected but its state indicates that we have
428            // nothing to do with it. Then, disconnect the service.
429            if (DEBUG) {
430                Slog.d(TAG, "unbindService(service=" + service + ")");
431            }
432            mContext.unbindService(serviceState.mConnection);
433            userState.serviceStateMap.remove(service);
434        }
435    }
436
437    private ClientState createClientStateLocked(IBinder clientToken, int userId) {
438        UserState userState = getUserStateLocked(userId);
439        ClientState clientState = new ClientState(clientToken, userId);
440        try {
441            clientToken.linkToDeath(clientState, 0);
442        } catch (RemoteException e) {
443            Slog.e(TAG, "Client is already died.");
444        }
445        userState.clientStateMap.put(clientToken, clientState);
446        return clientState;
447    }
448
449    private void createSessionInternalLocked(ITvInputService service, final IBinder sessionToken,
450            final int userId) {
451        final UserState userState = getUserStateLocked(userId);
452        final SessionState sessionState = userState.sessionStateMap.get(sessionToken);
453        if (DEBUG) {
454            Slog.d(TAG, "createSessionInternalLocked(inputId=" + sessionState.mInfo.getId() + ")");
455        }
456
457        final InputChannel[] channels = InputChannel.openInputChannelPair(sessionToken.toString());
458
459        // Set up a callback to send the session token.
460        ITvInputSessionCallback callback = new ITvInputSessionCallback.Stub() {
461            @Override
462            public void onSessionCreated(ITvInputSession session) {
463                if (DEBUG) {
464                    Slog.d(TAG, "onSessionCreated(inputId=" + sessionState.mInfo.getId() + ")");
465                }
466                synchronized (mLock) {
467                    sessionState.mSession = session;
468                    if (session == null) {
469                        removeSessionStateLocked(sessionToken, userId);
470                        sendSessionTokenToClientLocked(sessionState.mClient,
471                                sessionState.mInfo.getId(), null, null, sessionState.mSeq);
472                    } else {
473                        try {
474                            session.asBinder().linkToDeath(sessionState, 0);
475                        } catch (RemoteException e) {
476                            Slog.e(TAG, "Session is already died.");
477                        }
478
479                        IBinder clientToken = sessionState.mClient.asBinder();
480                        ClientState clientState = userState.clientStateMap.get(clientToken);
481                        if (clientState == null) {
482                            clientState = createClientStateLocked(clientToken, userId);
483                        }
484                        clientState.mSessionTokens.add(sessionState.mSessionToken);
485
486                        sendSessionTokenToClientLocked(sessionState.mClient,
487                                sessionState.mInfo.getId(), sessionToken, channels[0],
488                                sessionState.mSeq);
489                    }
490                    channels[0].dispose();
491                }
492            }
493
494            @Override
495            public void onChannelRetuned(Uri channelUri) {
496                synchronized (mLock) {
497                    if (DEBUG) {
498                        Slog.d(TAG, "onChannelRetuned(" + channelUri + ")");
499                    }
500                    if (sessionState.mSession == null || sessionState.mClient == null) {
501                        return;
502                    }
503                    try {
504                        // TODO: Consider adding this channel change in the watch log. When we do
505                        // that, how we can protect the watch log from malicious tv inputs should
506                        // be addressed. e.g. add a field which represents where the channel change
507                        // originated from.
508                        sessionState.mClient.onChannelRetuned(channelUri, sessionState.mSeq);
509                    } catch (RemoteException e) {
510                        Slog.e(TAG, "error in onChannelRetuned");
511                    }
512                }
513            }
514
515            @Override
516            public void onTrackInfoChanged(List<TvTrackInfo> tracks) {
517                synchronized (mLock) {
518                    if (DEBUG) {
519                        Slog.d(TAG, "onTrackInfoChanged(" + tracks + ")");
520                    }
521                    if (sessionState.mSession == null || sessionState.mClient == null) {
522                        return;
523                    }
524                    try {
525                        sessionState.mClient.onTrackInfoChanged(tracks,
526                                sessionState.mSeq);
527                    } catch (RemoteException e) {
528                        Slog.e(TAG, "error in onTrackInfoChanged");
529                    }
530                }
531            }
532
533            @Override
534            public void onVideoAvailable() {
535                synchronized (mLock) {
536                    if (DEBUG) {
537                        Slog.d(TAG, "onVideoAvailable()");
538                    }
539                    if (sessionState.mSession == null || sessionState.mClient == null) {
540                        return;
541                    }
542                    try {
543                        sessionState.mClient.onVideoAvailable(sessionState.mSeq);
544                    } catch (RemoteException e) {
545                        Slog.e(TAG, "error in onVideoAvailable");
546                    }
547                }
548            }
549
550            @Override
551            public void onVideoUnavailable(int reason) {
552                synchronized (mLock) {
553                    if (DEBUG) {
554                        Slog.d(TAG, "onVideoUnavailable(" + reason + ")");
555                    }
556                    if (sessionState.mSession == null || sessionState.mClient == null) {
557                        return;
558                    }
559                    try {
560                        sessionState.mClient.onVideoUnavailable(reason, sessionState.mSeq);
561                    } catch (RemoteException e) {
562                        Slog.e(TAG, "error in onVideoUnavailable");
563                    }
564                }
565            }
566
567            @Override
568            public void onContentBlocked(String rating) {
569                synchronized (mLock) {
570                    if (DEBUG) {
571                        Slog.d(TAG, "onContentBlocked()");
572                    }
573                    if (sessionState.mSession == null || sessionState.mClient == null) {
574                        return;
575                    }
576                    try {
577                        sessionState.mClient.onContentBlocked(rating, sessionState.mSeq);
578                    } catch (RemoteException e) {
579                        Slog.e(TAG, "error in onContentBlocked");
580                    }
581                }
582            }
583
584            @Override
585            public void onSessionEvent(String eventType, Bundle eventArgs) {
586                synchronized (mLock) {
587                    if (DEBUG) {
588                        Slog.d(TAG, "onEvent(what=" + eventType + ", data=" + eventArgs + ")");
589                    }
590                    if (sessionState.mSession == null || sessionState.mClient == null) {
591                        return;
592                    }
593                    try {
594                        sessionState.mClient.onSessionEvent(eventType, eventArgs,
595                                sessionState.mSeq);
596                    } catch (RemoteException e) {
597                        Slog.e(TAG, "error in onSessionEvent");
598                    }
599                }
600            }
601        };
602
603        // Create a session. When failed, send a null token immediately.
604        try {
605            service.createSession(channels[1], callback, sessionState.mInfo.getId());
606        } catch (RemoteException e) {
607            Slog.e(TAG, "error in createSession", e);
608            removeSessionStateLocked(sessionToken, userId);
609            sendSessionTokenToClientLocked(sessionState.mClient, sessionState.mInfo.getId(), null,
610                    null, sessionState.mSeq);
611        }
612        channels[1].dispose();
613    }
614
615    private void sendSessionTokenToClientLocked(ITvInputClient client, String inputId,
616            IBinder sessionToken, InputChannel channel, int seq) {
617        try {
618            client.onSessionCreated(inputId, sessionToken, channel, seq);
619        } catch (RemoteException exception) {
620            Slog.e(TAG, "error in onSessionCreated", exception);
621        }
622    }
623
624    private void releaseSessionLocked(IBinder sessionToken, int callingUid, int userId) {
625        SessionState sessionState = getSessionStateLocked(sessionToken, callingUid, userId);
626        if (sessionState.mSession != null) {
627            try {
628                sessionState.mSession.release();
629            } catch (RemoteException e) {
630                Slog.w(TAG, "session is already disapeared", e);
631            }
632            sessionState.mSession = null;
633        }
634        removeSessionStateLocked(sessionToken, userId);
635    }
636
637    private void removeSessionStateLocked(IBinder sessionToken, int userId) {
638        // Remove the session state from the global session state map of the current user.
639        UserState userState = getUserStateLocked(userId);
640        SessionState sessionState = userState.sessionStateMap.remove(sessionToken);
641
642        // Close the open log entry, if any.
643        if (sessionState.mLogUri != null) {
644            SomeArgs args = SomeArgs.obtain();
645            args.arg1 = sessionState.mLogUri;
646            args.arg2 = System.currentTimeMillis();
647            mLogHandler.obtainMessage(LogHandler.MSG_CLOSE_ENTRY, args).sendToTarget();
648        }
649
650        // Also remove the session token from the session token list of the current client and
651        // service.
652        ClientState clientState = userState.clientStateMap.get(sessionState.mClient.asBinder());
653        if (clientState != null) {
654            clientState.mSessionTokens.remove(sessionToken);
655            if (clientState.isEmpty()) {
656                userState.clientStateMap.remove(sessionState.mClient.asBinder());
657            }
658        }
659
660        TvInputInfo info = sessionState.mInfo;
661        if (info != null) {
662            ServiceState serviceState = userState.serviceStateMap.get(info.getComponent());
663            if (serviceState != null) {
664                serviceState.mSessionTokens.remove(sessionToken);
665            }
666        }
667        updateServiceConnectionLocked(sessionState.mInfo.getComponent(), userId);
668    }
669
670    private void unregisterClientInternalLocked(IBinder clientToken, String inputId,
671            int userId) {
672        UserState userState = getUserStateLocked(userId);
673        ClientState clientState = userState.clientStateMap.get(clientToken);
674        if (clientState != null) {
675            clientState.mInputIds.remove(inputId);
676            if (clientState.isEmpty()) {
677                userState.clientStateMap.remove(clientToken);
678            }
679        }
680
681        TvInputInfo info = userState.inputMap.get(inputId).mInfo;
682        if (info == null) {
683            return;
684        }
685        ServiceState serviceState = userState.serviceStateMap.get(info.getComponent());
686        if (serviceState == null) {
687            return;
688        }
689
690        // Remove this client from the client list and unregister the callback.
691        serviceState.mClientTokens.remove(clientToken);
692        if (!serviceState.mClientTokens.isEmpty()) {
693            // We have other clients who want to keep the callback. Do this later.
694            return;
695        }
696        if (serviceState.mService == null || serviceState.mCallback == null) {
697            return;
698        }
699        try {
700            serviceState.mService.unregisterCallback(serviceState.mCallback);
701        } catch (RemoteException e) {
702            Slog.e(TAG, "error in unregisterCallback", e);
703        } finally {
704            serviceState.mCallback = null;
705            updateServiceConnectionLocked(info.getComponent(), userId);
706        }
707    }
708
709    private void notifyInputAddedLocked(UserState userState, String inputId) {
710        if (DEBUG) {
711            Slog.d(TAG, "notifyInputAdded: inputId = " + inputId);
712        }
713        for (ITvInputManagerCallback callback : userState.callbackSet) {
714            try {
715                callback.onInputAdded(inputId);
716            } catch (RemoteException e) {
717                Slog.e(TAG, "Failed to report added input to callback.");
718            }
719        }
720    }
721
722    private void notifyInputRemovedLocked(UserState userState, String inputId) {
723        if (DEBUG) {
724            Slog.d(TAG, "notifyInputRemovedLocked: inputId = " + inputId);
725        }
726        for (ITvInputManagerCallback callback : userState.callbackSet) {
727            try {
728                callback.onInputRemoved(inputId);
729            } catch (RemoteException e) {
730                Slog.e(TAG, "Failed to report removed input to callback.");
731            }
732        }
733    }
734
735    private void notifyInputStateChangedLocked(UserState userState, String inputId,
736            int state, ITvInputManagerCallback targetCallback) {
737        if (DEBUG) {
738            Slog.d(TAG, "notifyInputStateChangedLocked: inputId = " + inputId
739                    + "; state = " + state);
740        }
741        if (targetCallback == null) {
742            for (ITvInputManagerCallback callback : userState.callbackSet) {
743                try {
744                    callback.onInputStateChanged(inputId, state);
745                } catch (RemoteException e) {
746                    Slog.e(TAG, "Failed to report state change to callback.");
747                }
748            }
749        } else {
750            try {
751                targetCallback.onInputStateChanged(inputId, state);
752            } catch (RemoteException e) {
753                Slog.e(TAG, "Failed to report state change to callback.");
754            }
755        }
756    }
757
758    private void setStateLocked(String inputId, int state, int userId) {
759        UserState userState = getUserStateLocked(userId);
760        TvInputState inputState = userState.inputMap.get(inputId);
761        ServiceState serviceState = userState.serviceStateMap.get(inputId);
762        int oldState = inputState.mState;
763        inputState.mState = state;
764        if (serviceState != null && serviceState.mService == null
765                && shouldMaintainConnection(serviceState)) {
766            // We don't notify state change while reconnecting. It should remain disconnected.
767            return;
768        }
769        if (oldState != state) {
770            notifyInputStateChangedLocked(userState, inputId, state, null);
771        }
772    }
773
774    private final class BinderService extends ITvInputManager.Stub {
775        @Override
776        public List<TvInputInfo> getTvInputList(int userId) {
777            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(),
778                    Binder.getCallingUid(), userId, "getTvInputList");
779            final long identity = Binder.clearCallingIdentity();
780            try {
781                synchronized (mLock) {
782                    UserState userState = getUserStateLocked(resolvedUserId);
783                    List<TvInputInfo> inputList = new ArrayList<TvInputInfo>();
784                    for (TvInputState state : userState.inputMap.values()) {
785                        inputList.add(state.mInfo);
786                    }
787                    return inputList;
788                }
789            } finally {
790                Binder.restoreCallingIdentity(identity);
791            }
792        }
793
794        @Override
795        public TvInputInfo getTvInputInfo(String inputId, int userId) {
796            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(),
797                    Binder.getCallingUid(), userId, "getTvInputInfo");
798            final long identity = Binder.clearCallingIdentity();
799            try {
800                synchronized (mLock) {
801                    UserState userState = getUserStateLocked(resolvedUserId);
802                    TvInputState state = userState.inputMap.get(inputId);
803                    return state == null ? null : state.mInfo;
804                }
805            } finally {
806                Binder.restoreCallingIdentity(identity);
807            }
808        }
809
810        @Override
811        public void registerCallback(final ITvInputManagerCallback callback, int userId) {
812            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(),
813                    Binder.getCallingUid(), userId, "registerCallback");
814            final long identity = Binder.clearCallingIdentity();
815            try {
816                synchronized (mLock) {
817                    UserState userState = getUserStateLocked(resolvedUserId);
818                    userState.callbackSet.add(callback);
819                    for (TvInputState state : userState.inputMap.values()) {
820                        notifyInputStateChangedLocked(userState, state.mInfo.getId(),
821                                state.mState, callback);
822                    }
823                }
824            } finally {
825                Binder.restoreCallingIdentity(identity);
826            }
827        }
828
829        @Override
830        public void unregisterCallback(ITvInputManagerCallback callback, int userId) {
831            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(),
832                    Binder.getCallingUid(), userId, "unregisterCallback");
833            final long identity = Binder.clearCallingIdentity();
834            try {
835                synchronized (mLock) {
836                    UserState userState = getUserStateLocked(resolvedUserId);
837                    userState.callbackSet.remove(callback);
838                }
839            } finally {
840                Binder.restoreCallingIdentity(identity);
841            }
842        }
843
844        @Override
845        public void createSession(final ITvInputClient client, final String inputId,
846                int seq, int userId) {
847            final int callingUid = Binder.getCallingUid();
848            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
849                    userId, "createSession");
850            final long identity = Binder.clearCallingIdentity();
851            try {
852                synchronized (mLock) {
853                    UserState userState = getUserStateLocked(resolvedUserId);
854                    TvInputInfo info = userState.inputMap.get(inputId).mInfo;
855                    ServiceState serviceState = userState.serviceStateMap.get(info.getComponent());
856                    if (serviceState == null) {
857                        serviceState = new ServiceState(info.getComponent(), resolvedUserId);
858                        userState.serviceStateMap.put(info.getComponent(), serviceState);
859                    }
860                    // Send a null token immediately while reconnecting.
861                    if (serviceState.mReconnecting == true) {
862                        sendSessionTokenToClientLocked(client, inputId, null, null, seq);
863                        return;
864                    }
865
866                    // Create a new session token and a session state.
867                    IBinder sessionToken = new Binder();
868                    SessionState sessionState = new SessionState(sessionToken, info, client,
869                            seq, callingUid, resolvedUserId);
870
871                    // Add them to the global session state map of the current user.
872                    userState.sessionStateMap.put(sessionToken, sessionState);
873
874                    // Also, add them to the session state map of the current service.
875                    serviceState.mSessionTokens.add(sessionToken);
876
877                    if (serviceState.mService != null) {
878                        createSessionInternalLocked(serviceState.mService, sessionToken,
879                                resolvedUserId);
880                    } else {
881                        updateServiceConnectionLocked(info.getComponent(), resolvedUserId);
882                    }
883                }
884            } finally {
885                Binder.restoreCallingIdentity(identity);
886            }
887        }
888
889        @Override
890        public void releaseSession(IBinder sessionToken, int userId) {
891            final int callingUid = Binder.getCallingUid();
892            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
893                    userId, "releaseSession");
894            final long identity = Binder.clearCallingIdentity();
895            try {
896                synchronized (mLock) {
897                    releaseSessionLocked(sessionToken, callingUid, resolvedUserId);
898                }
899            } finally {
900                Binder.restoreCallingIdentity(identity);
901            }
902        }
903
904        @Override
905        public void setSurface(IBinder sessionToken, Surface surface, int userId) {
906            final int callingUid = Binder.getCallingUid();
907            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
908                    userId, "setSurface");
909            final long identity = Binder.clearCallingIdentity();
910            try {
911                synchronized (mLock) {
912                    try {
913                        getSessionLocked(sessionToken, callingUid, resolvedUserId).setSurface(
914                                surface);
915                    } catch (RemoteException e) {
916                        Slog.e(TAG, "error in setSurface", e);
917                    }
918                }
919            } finally {
920                if (surface != null) {
921                    // surface is not used in TvInputManagerService.
922                    surface.release();
923                }
924                Binder.restoreCallingIdentity(identity);
925            }
926        }
927
928        @Override
929        public void dispatchSurfaceChanged(IBinder sessionToken, int format, int width,
930                int height, int userId) {
931            final int callingUid = Binder.getCallingUid();
932            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
933                    userId, "dispatchSurfaceChanged");
934            final long identity = Binder.clearCallingIdentity();
935            try {
936                synchronized (mLock) {
937                    try {
938                        getSessionLocked(sessionToken, callingUid, resolvedUserId)
939                                .dispatchSurfaceChanged(format, width, height);
940                    } catch (RemoteException e) {
941                        Slog.e(TAG, "error in dispatchSurfaceChanged", e);
942                    }
943                }
944            } finally {
945                Binder.restoreCallingIdentity(identity);
946            }
947        }
948
949        @Override
950        public void setVolume(IBinder sessionToken, float volume, int userId) {
951            final int callingUid = Binder.getCallingUid();
952            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
953                    userId, "setVolume");
954            final long identity = Binder.clearCallingIdentity();
955            try {
956                synchronized (mLock) {
957                    try {
958                        getSessionLocked(sessionToken, callingUid, resolvedUserId).setVolume(
959                                volume);
960                    } catch (RemoteException e) {
961                        Slog.e(TAG, "error in setVolume", e);
962                    }
963                }
964            } finally {
965                Binder.restoreCallingIdentity(identity);
966            }
967        }
968
969        @Override
970        public void tune(IBinder sessionToken, final Uri channelUri, int userId) {
971            final int callingUid = Binder.getCallingUid();
972            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
973                    userId, "tune");
974            final long identity = Binder.clearCallingIdentity();
975            try {
976                synchronized (mLock) {
977                    try {
978                        getSessionLocked(sessionToken, callingUid, resolvedUserId).tune(channelUri);
979
980                        long currentTime = System.currentTimeMillis();
981                        long channelId = ContentUris.parseId(channelUri);
982
983                        // Close the open log entry first, if any.
984                        UserState userState = getUserStateLocked(resolvedUserId);
985                        SessionState sessionState = userState.sessionStateMap.get(sessionToken);
986                        if (sessionState.mLogUri != null) {
987                            SomeArgs args = SomeArgs.obtain();
988                            args.arg1 = sessionState.mLogUri;
989                            args.arg2 = currentTime;
990                            mLogHandler.obtainMessage(LogHandler.MSG_CLOSE_ENTRY, args)
991                                    .sendToTarget();
992                        }
993
994                        // Create a log entry and fill it later.
995                        String packageName = sessionState.mInfo.getServiceInfo().packageName;
996                        ContentValues values = new ContentValues();
997                        values.put(TvContract.WatchedPrograms.COLUMN_PACKAGE_NAME, packageName);
998                        values.put(TvContract.WatchedPrograms.COLUMN_WATCH_START_TIME_UTC_MILLIS,
999                                currentTime);
1000                        values.put(TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS, 0);
1001                        values.put(TvContract.WatchedPrograms.COLUMN_CHANNEL_ID, channelId);
1002
1003                        sessionState.mLogUri = mContentResolver.insert(
1004                                TvContract.WatchedPrograms.CONTENT_URI, values);
1005                        SomeArgs args = SomeArgs.obtain();
1006                        args.arg1 = sessionState.mLogUri;
1007                        args.arg2 = ContentUris.parseId(channelUri);
1008                        args.arg3 = currentTime;
1009                        mLogHandler.obtainMessage(LogHandler.MSG_OPEN_ENTRY, args).sendToTarget();
1010                    } catch (RemoteException e) {
1011                        Slog.e(TAG, "error in tune", e);
1012                        return;
1013                    }
1014                }
1015            } finally {
1016                Binder.restoreCallingIdentity(identity);
1017            }
1018        }
1019
1020        @Override
1021        public void setCaptionEnabled(IBinder sessionToken, boolean enabled, int userId) {
1022            final int callingUid = Binder.getCallingUid();
1023            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1024                    userId, "setCaptionEnabled");
1025            final long identity = Binder.clearCallingIdentity();
1026            try {
1027                synchronized (mLock) {
1028                    try {
1029                        getSessionLocked(sessionToken, callingUid, resolvedUserId)
1030                                .setCaptionEnabled(enabled);
1031                    } catch (RemoteException e) {
1032                        Slog.e(TAG, "error in setCaptionEnabled", e);
1033                    }
1034                }
1035            } finally {
1036                Binder.restoreCallingIdentity(identity);
1037            }
1038        }
1039
1040        @Override
1041        public void selectTrack(IBinder sessionToken, TvTrackInfo track, int userId) {
1042            final int callingUid = Binder.getCallingUid();
1043            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1044                    userId, "selectTrack");
1045            final long identity = Binder.clearCallingIdentity();
1046            try {
1047                synchronized (mLock) {
1048                    try {
1049                        getSessionLocked(sessionToken, callingUid, resolvedUserId).selectTrack(
1050                                track);
1051                    } catch (RemoteException e) {
1052                        Slog.e(TAG, "error in selectTrack", e);
1053                    }
1054                }
1055            } finally {
1056                Binder.restoreCallingIdentity(identity);
1057            }
1058        }
1059
1060        @Override
1061        public void unselectTrack(IBinder sessionToken, TvTrackInfo track, int userId) {
1062            final int callingUid = Binder.getCallingUid();
1063            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1064                    userId, "unselectTrack");
1065            final long identity = Binder.clearCallingIdentity();
1066            try {
1067                synchronized (mLock) {
1068                    try {
1069                        getSessionLocked(sessionToken, callingUid, resolvedUserId).unselectTrack(
1070                                track);
1071                    } catch (RemoteException e) {
1072                        Slog.e(TAG, "error in unselectTrack", e);
1073                    }
1074                }
1075            } finally {
1076                Binder.restoreCallingIdentity(identity);
1077            }
1078        }
1079
1080        @Override
1081        public void createOverlayView(IBinder sessionToken, IBinder windowToken, Rect frame,
1082                int userId) {
1083            final int callingUid = Binder.getCallingUid();
1084            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1085                    userId, "createOverlayView");
1086            final long identity = Binder.clearCallingIdentity();
1087            try {
1088                synchronized (mLock) {
1089                    try {
1090                        getSessionLocked(sessionToken, callingUid, resolvedUserId)
1091                                .createOverlayView(windowToken, frame);
1092                    } catch (RemoteException e) {
1093                        Slog.e(TAG, "error in createOverlayView", e);
1094                    }
1095                }
1096            } finally {
1097                Binder.restoreCallingIdentity(identity);
1098            }
1099        }
1100
1101        @Override
1102        public void relayoutOverlayView(IBinder sessionToken, Rect frame, int userId) {
1103            final int callingUid = Binder.getCallingUid();
1104            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1105                    userId, "relayoutOverlayView");
1106            final long identity = Binder.clearCallingIdentity();
1107            try {
1108                synchronized (mLock) {
1109                    try {
1110                        getSessionLocked(sessionToken, callingUid, resolvedUserId)
1111                                .relayoutOverlayView(frame);
1112                    } catch (RemoteException e) {
1113                        Slog.e(TAG, "error in relayoutOverlayView", e);
1114                    }
1115                }
1116            } finally {
1117                Binder.restoreCallingIdentity(identity);
1118            }
1119        }
1120
1121        @Override
1122        public void removeOverlayView(IBinder sessionToken, int userId) {
1123            final int callingUid = Binder.getCallingUid();
1124            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1125                    userId, "removeOverlayView");
1126            final long identity = Binder.clearCallingIdentity();
1127            try {
1128                synchronized (mLock) {
1129                    try {
1130                        getSessionLocked(sessionToken, callingUid, resolvedUserId)
1131                                .removeOverlayView();
1132                    } catch (RemoteException e) {
1133                        Slog.e(TAG, "error in removeOverlayView", e);
1134                    }
1135                }
1136            } finally {
1137                Binder.restoreCallingIdentity(identity);
1138            }
1139        }
1140
1141        @Override
1142        public List<TvInputHardwareInfo> getHardwareList() throws RemoteException {
1143            if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1144                    != PackageManager.PERMISSION_GRANTED) {
1145                return null;
1146            }
1147
1148            final long identity = Binder.clearCallingIdentity();
1149            try {
1150                return mTvInputHardwareManager.getHardwareList();
1151            } finally {
1152                Binder.restoreCallingIdentity(identity);
1153            }
1154        }
1155
1156        @Override
1157        public void registerTvInputInfo(TvInputInfo info, int deviceId) {
1158            // TODO: Revisit to sort out deviceId ownership.
1159            if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1160                    != PackageManager.PERMISSION_GRANTED) {
1161                return;
1162            }
1163
1164            final long identity = Binder.clearCallingIdentity();
1165            try {
1166                mTvInputHardwareManager.registerTvInputInfo(info, deviceId);
1167            } finally {
1168                Binder.restoreCallingIdentity(identity);
1169            }
1170        }
1171
1172        @Override
1173        public ITvInputHardware acquireTvInputHardware(int deviceId,
1174                ITvInputHardwareCallback callback, TvInputInfo info, int userId)
1175                throws RemoteException {
1176            if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1177                    != PackageManager.PERMISSION_GRANTED) {
1178                return null;
1179            }
1180
1181            final long identity = Binder.clearCallingIdentity();
1182            final int callingUid = Binder.getCallingUid();
1183            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1184                    userId, "acquireTvInputHardware");
1185            try {
1186                return mTvInputHardwareManager.acquireHardware(
1187                        deviceId, callback, info, callingUid, resolvedUserId);
1188            } finally {
1189                Binder.restoreCallingIdentity(identity);
1190            }
1191        }
1192
1193        @Override
1194        public void releaseTvInputHardware(int deviceId, ITvInputHardware hardware, int userId)
1195                throws RemoteException {
1196            if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1197                    != PackageManager.PERMISSION_GRANTED) {
1198                return;
1199            }
1200
1201            final long identity = Binder.clearCallingIdentity();
1202            final int callingUid = Binder.getCallingUid();
1203            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1204                    userId, "releaseTvInputHardware");
1205            try {
1206                mTvInputHardwareManager.releaseHardware(
1207                        deviceId, hardware, callingUid, resolvedUserId);
1208            } finally {
1209                Binder.restoreCallingIdentity(identity);
1210            }
1211        }
1212
1213        @Override
1214        @SuppressWarnings("resource")
1215        protected void dump(FileDescriptor fd, final PrintWriter writer, String[] args) {
1216            final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
1217            if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1218                    != PackageManager.PERMISSION_GRANTED) {
1219                pw.println("Permission Denial: can't dump TvInputManager from pid="
1220                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
1221                return;
1222            }
1223
1224            synchronized (mLock) {
1225                pw.println("User Ids (Current user: " + mCurrentUserId + "):");
1226                pw.increaseIndent();
1227                for (int i = 0; i < mUserStates.size(); i++) {
1228                    int userId = mUserStates.keyAt(i);
1229                    pw.println(Integer.valueOf(userId));
1230                }
1231                pw.decreaseIndent();
1232
1233                for (int i = 0; i < mUserStates.size(); i++) {
1234                    int userId = mUserStates.keyAt(i);
1235                    UserState userState = getUserStateLocked(userId);
1236                    pw.println("UserState (" + userId + "):");
1237                    pw.increaseIndent();
1238
1239                    pw.println("inputMap: inputId -> TvInputState");
1240                    pw.increaseIndent();
1241                    for (Map.Entry<String, TvInputState> entry: userState.inputMap.entrySet()) {
1242                        pw.println(entry.getKey() + ": " + entry.getValue());
1243                    }
1244                    pw.decreaseIndent();
1245
1246                    pw.println("packageSet:");
1247                    pw.increaseIndent();
1248                    for (String packageName : userState.packageSet) {
1249                        pw.println(packageName);
1250                    }
1251                    pw.decreaseIndent();
1252
1253                    pw.println("clientStateMap: ITvInputClient -> ClientState");
1254                    pw.increaseIndent();
1255                    for (Map.Entry<IBinder, ClientState> entry :
1256                            userState.clientStateMap.entrySet()) {
1257                        ClientState client = entry.getValue();
1258                        pw.println(entry.getKey() + ": " + client);
1259
1260                        pw.increaseIndent();
1261
1262                        pw.println("mInputIds:");
1263                        pw.increaseIndent();
1264                        for (String inputId : client.mInputIds) {
1265                            pw.println(inputId);
1266                        }
1267                        pw.decreaseIndent();
1268
1269                        pw.println("mSessionTokens:");
1270                        pw.increaseIndent();
1271                        for (IBinder token : client.mSessionTokens) {
1272                            pw.println("" + token);
1273                        }
1274                        pw.decreaseIndent();
1275
1276                        pw.println("mClientTokens: " + client.mClientToken);
1277                        pw.println("mUserId: " + client.mUserId);
1278
1279                        pw.decreaseIndent();
1280                    }
1281                    pw.decreaseIndent();
1282
1283                    pw.println("serviceStateMap: ComponentName -> ServiceState");
1284                    pw.increaseIndent();
1285                    for (Map.Entry<ComponentName, ServiceState> entry :
1286                            userState.serviceStateMap.entrySet()) {
1287                        ServiceState service = entry.getValue();
1288                        pw.println(entry.getKey() + ": " + service);
1289
1290                        pw.increaseIndent();
1291
1292                        pw.println("mClientTokens:");
1293                        pw.increaseIndent();
1294                        for (IBinder token : service.mClientTokens) {
1295                            pw.println("" + token);
1296                        }
1297                        pw.decreaseIndent();
1298
1299                        pw.println("mSessionTokens:");
1300                        pw.increaseIndent();
1301                        for (IBinder token : service.mSessionTokens) {
1302                            pw.println("" + token);
1303                        }
1304                        pw.decreaseIndent();
1305
1306                        pw.println("mService: " + service.mService);
1307                        pw.println("mCallback: " + service.mCallback);
1308                        pw.println("mBound: " + service.mBound);
1309                        pw.println("mReconnecting: " + service.mReconnecting);
1310
1311                        pw.decreaseIndent();
1312                    }
1313                    pw.decreaseIndent();
1314
1315                    pw.println("sessionStateMap: ITvInputSession -> SessionState");
1316                    pw.increaseIndent();
1317                    for (Map.Entry<IBinder, SessionState> entry :
1318                            userState.sessionStateMap.entrySet()) {
1319                        SessionState session = entry.getValue();
1320                        pw.println(entry.getKey() + ": " + session);
1321
1322                        pw.increaseIndent();
1323                        pw.println("mInfo: " + session.mInfo);
1324                        pw.println("mClient: " + session.mClient);
1325                        pw.println("mSeq: " + session.mSeq);
1326                        pw.println("mCallingUid: " + session.mCallingUid);
1327                        pw.println("mUserId: " + session.mUserId);
1328                        pw.println("mSessionToken: " + session.mSessionToken);
1329                        pw.println("mSession: " + session.mSession);
1330                        pw.println("mLogUri: " + session.mLogUri);
1331                        pw.decreaseIndent();
1332                    }
1333                    pw.decreaseIndent();
1334
1335                    pw.println("callbackSet:");
1336                    pw.increaseIndent();
1337                    for (ITvInputManagerCallback callback : userState.callbackSet) {
1338                        pw.println(callback.toString());
1339                    }
1340                    pw.decreaseIndent();
1341
1342                    pw.decreaseIndent();
1343                }
1344            }
1345        }
1346    }
1347
1348    private static final class TvInputState {
1349        // A TvInputInfo object which represents the TV input.
1350        private TvInputInfo mInfo;
1351
1352        // The state of TV input. Connected by default.
1353        private int mState = INPUT_STATE_CONNECTED;
1354
1355        @Override
1356        public String toString() {
1357            return "mInfo: " + mInfo + "; mState: " + mState;
1358        }
1359    }
1360
1361    private static final class UserState {
1362        // A mapping from the TV input id to its TvInputState.
1363        private Map<String, TvInputState> inputMap = new HashMap<String, TvInputState>();
1364
1365        // A set of all TV input packages.
1366        private final Set<String> packageSet = new HashSet<String>();
1367
1368        // A mapping from the token of a client to its state.
1369        private final Map<IBinder, ClientState> clientStateMap =
1370                new HashMap<IBinder, ClientState>();
1371
1372        // A mapping from the name of a TV input service to its state.
1373        private final Map<ComponentName, ServiceState> serviceStateMap =
1374                new HashMap<ComponentName, ServiceState>();
1375
1376        // A mapping from the token of a TV input session to its state.
1377        private final Map<IBinder, SessionState> sessionStateMap =
1378                new HashMap<IBinder, SessionState>();
1379
1380        // A set of callbacks.
1381        private final Set<ITvInputManagerCallback> callbackSet =
1382                new HashSet<ITvInputManagerCallback>();
1383    }
1384
1385    private final class ClientState implements IBinder.DeathRecipient {
1386        private final List<String> mInputIds = new ArrayList<String>();
1387        private final List<IBinder> mSessionTokens = new ArrayList<IBinder>();
1388
1389        private IBinder mClientToken;
1390        private final int mUserId;
1391
1392        ClientState(IBinder clientToken, int userId) {
1393            mClientToken = clientToken;
1394            mUserId = userId;
1395        }
1396
1397        public boolean isEmpty() {
1398            return mInputIds.isEmpty() && mSessionTokens.isEmpty();
1399        }
1400
1401        @Override
1402        public void binderDied() {
1403            synchronized (mLock) {
1404                UserState userState = getUserStateLocked(mUserId);
1405                // DO NOT remove the client state of clientStateMap in this method. It will be
1406                // removed in releaseSessionLocked() or unregisterClientInternalLocked().
1407                ClientState clientState = userState.clientStateMap.get(mClientToken);
1408                if (clientState != null) {
1409                    while (clientState.mSessionTokens.size() > 0) {
1410                        releaseSessionLocked(
1411                                clientState.mSessionTokens.get(0), Process.SYSTEM_UID, mUserId);
1412                    }
1413                    while (clientState.mInputIds.size() > 0) {
1414                        unregisterClientInternalLocked(
1415                                mClientToken, clientState.mInputIds.get(0), mUserId);
1416                    }
1417                }
1418                mClientToken = null;
1419            }
1420        }
1421    }
1422
1423    private final class ServiceState {
1424        private final List<IBinder> mClientTokens = new ArrayList<IBinder>();
1425        private final List<IBinder> mSessionTokens = new ArrayList<IBinder>();
1426        private final ServiceConnection mConnection;
1427        private final ComponentName mName;
1428        private final boolean mIsHardware;
1429        private final List<TvInputInfo> mInputList = new ArrayList<TvInputInfo>();
1430
1431        private ITvInputService mService;
1432        private ServiceCallback mCallback;
1433        private boolean mBound;
1434        private boolean mReconnecting;
1435
1436        private ServiceState(ComponentName name, int userId) {
1437            mName = name;
1438            mConnection = new InputServiceConnection(name, userId);
1439            mIsHardware = hasHardwarePermission(mContext.getPackageManager(), mName);
1440        }
1441    }
1442
1443    private final class SessionState implements IBinder.DeathRecipient {
1444        private final TvInputInfo mInfo;
1445        private final ITvInputClient mClient;
1446        private final int mSeq;
1447        private final int mCallingUid;
1448        private final int mUserId;
1449        private final IBinder mSessionToken;
1450        private ITvInputSession mSession;
1451        private Uri mLogUri;
1452
1453        private SessionState(IBinder sessionToken, TvInputInfo info, ITvInputClient client, int seq,
1454                int callingUid, int userId) {
1455            mSessionToken = sessionToken;
1456            mInfo = info;
1457            mClient = client;
1458            mSeq = seq;
1459            mCallingUid = callingUid;
1460            mUserId = userId;
1461        }
1462
1463        @Override
1464        public void binderDied() {
1465            synchronized (mLock) {
1466                mSession = null;
1467                if (mClient != null) {
1468                    try {
1469                        mClient.onSessionReleased(mSeq);
1470                    } catch(RemoteException e) {
1471                        Slog.e(TAG, "error in onSessionReleased", e);
1472                    }
1473                }
1474                removeSessionStateLocked(mSessionToken, mUserId);
1475            }
1476        }
1477    }
1478
1479    private final class InputServiceConnection implements ServiceConnection {
1480        private final ComponentName mName;
1481        private final int mUserId;
1482
1483        private InputServiceConnection(ComponentName name, int userId) {
1484            mName = name;
1485            mUserId = userId;
1486        }
1487
1488        @Override
1489        public void onServiceConnected(ComponentName name, IBinder service) {
1490            if (DEBUG) {
1491                Slog.d(TAG, "onServiceConnected(name=" + name + ")");
1492            }
1493            synchronized (mLock) {
1494                List<TvInputHardwareInfo> hardwareInfoList =
1495                        mTvInputHardwareManager.getHardwareList();
1496                UserState userState = getUserStateLocked(mUserId);
1497                ServiceState serviceState = userState.serviceStateMap.get(mName);
1498                serviceState.mService = ITvInputService.Stub.asInterface(service);
1499
1500                // Register a callback, if we need to.
1501                if (serviceState.mIsHardware && serviceState.mCallback == null) {
1502                    serviceState.mCallback = new ServiceCallback(mName, mUserId);
1503                    try {
1504                        serviceState.mService.registerCallback(serviceState.mCallback);
1505                    } catch (RemoteException e) {
1506                        Slog.e(TAG, "error in registerCallback", e);
1507                    }
1508                }
1509
1510                // And create sessions, if any.
1511                for (IBinder sessionToken : serviceState.mSessionTokens) {
1512                    createSessionInternalLocked(serviceState.mService, sessionToken, mUserId);
1513                }
1514
1515                for (TvInputState inputState : userState.inputMap.values()) {
1516                    if (inputState.mInfo.getComponent().equals(name)
1517                            && inputState.mState != INPUT_STATE_DISCONNECTED) {
1518                        notifyInputStateChangedLocked(userState, inputState.mInfo.getId(),
1519                                inputState.mState, null);
1520                    }
1521                }
1522
1523                if (serviceState.mIsHardware) {
1524                    for (TvInputHardwareInfo hardwareInfo : hardwareInfoList) {
1525                        try {
1526                            serviceState.mService.notifyHardwareAdded(hardwareInfo);
1527                        } catch (RemoteException e) {
1528                            Slog.e(TAG, "error in notifyHardwareAdded", e);
1529                        }
1530                    }
1531
1532                    // TODO: Grab CEC devices and notify them to the service.
1533                }
1534            }
1535        }
1536
1537        @Override
1538        public void onServiceDisconnected(ComponentName name) {
1539            if (DEBUG) {
1540                Slog.d(TAG, "onServiceDisconnected(name=" + name + ")");
1541            }
1542            if (!mName.equals(name)) {
1543                throw new IllegalArgumentException("Mismatched ComponentName: "
1544                        + mName + " (expected), " + name + " (actual).");
1545            }
1546            synchronized (mLock) {
1547                UserState userState = getUserStateLocked(mUserId);
1548                ServiceState serviceState = userState.serviceStateMap.get(mName);
1549                if (serviceState != null) {
1550                    serviceState.mReconnecting = true;
1551                    serviceState.mBound = false;
1552                    serviceState.mService = null;
1553                    serviceState.mCallback = null;
1554
1555                    // Send null tokens for not finishing create session events.
1556                    for (IBinder sessionToken : serviceState.mSessionTokens) {
1557                        SessionState sessionState = userState.sessionStateMap.get(sessionToken);
1558                        if (sessionState.mSession == null) {
1559                            removeSessionStateLocked(sessionToken, sessionState.mUserId);
1560                            sendSessionTokenToClientLocked(sessionState.mClient,
1561                                    sessionState.mInfo.getId(), null, null, sessionState.mSeq);
1562                        }
1563                    }
1564
1565                    for (TvInputState inputState : userState.inputMap.values()) {
1566                        if (inputState.mInfo.getComponent().equals(name)) {
1567                            notifyInputStateChangedLocked(userState, inputState.mInfo.getId(),
1568                                    INPUT_STATE_DISCONNECTED, null);
1569                        }
1570                    }
1571                    updateServiceConnectionLocked(mName, mUserId);
1572                }
1573            }
1574        }
1575    }
1576
1577    private final class ServiceCallback extends ITvInputServiceCallback.Stub {
1578        private final ComponentName mName;
1579        private final int mUserId;
1580
1581        ServiceCallback(ComponentName name, int userId) {
1582            mName = name;
1583            mUserId = userId;
1584        }
1585
1586        @Override
1587        public void addTvInput(TvInputInfo inputInfo) {
1588            synchronized (mLock) {
1589                if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1590                        != PackageManager.PERMISSION_GRANTED) {
1591                    Slog.w(TAG, "The caller does not have permission to add a TV input ("
1592                            + inputInfo + ").");
1593                    return;
1594                }
1595
1596                ServiceState serviceState = getServiceStateLocked(mName, mUserId);
1597                serviceState.mInputList.add(inputInfo);
1598                buildTvInputListLocked(mUserId);
1599            }
1600        }
1601
1602        @Override
1603        public void removeTvInput(String inputId) {
1604            synchronized (mLock) {
1605                if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1606                        != PackageManager.PERMISSION_GRANTED) {
1607                    Slog.w(TAG, "The caller does not have permission to remove a TV input ("
1608                            + inputId + ").");
1609                    return;
1610                }
1611
1612                ServiceState serviceState = getServiceStateLocked(mName, mUserId);
1613                boolean removed = false;
1614                for (Iterator<TvInputInfo> it = serviceState.mInputList.iterator();
1615                        it.hasNext(); ) {
1616                    if (it.next().getId().equals(inputId)) {
1617                        it.remove();
1618                        removed = true;
1619                        break;
1620                    }
1621                }
1622                if (removed) {
1623                    buildTvInputListLocked(mUserId);
1624                } else {
1625                    Slog.e(TAG, "TvInputInfo with inputId=" + inputId + " not found.");
1626                }
1627            }
1628        }
1629    }
1630
1631    private final class LogHandler extends Handler {
1632        private static final int MSG_OPEN_ENTRY = 1;
1633        private static final int MSG_UPDATE_ENTRY = 2;
1634        private static final int MSG_CLOSE_ENTRY = 3;
1635
1636        public LogHandler(Looper looper) {
1637            super(looper);
1638        }
1639
1640        @Override
1641        public void handleMessage(Message msg) {
1642            switch (msg.what) {
1643                case MSG_OPEN_ENTRY: {
1644                    SomeArgs args = (SomeArgs) msg.obj;
1645                    Uri uri = (Uri) args.arg1;
1646                    long channelId = (long) args.arg2;
1647                    long time = (long) args.arg3;
1648                    onOpenEntry(uri, channelId, time);
1649                    args.recycle();
1650                    return;
1651                }
1652                case MSG_UPDATE_ENTRY: {
1653                    SomeArgs args = (SomeArgs) msg.obj;
1654                    Uri uri = (Uri) args.arg1;
1655                    long channelId = (long) args.arg2;
1656                    long time = (long) args.arg3;
1657                    onUpdateEntry(uri, channelId, time);
1658                    args.recycle();
1659                    return;
1660                }
1661                case MSG_CLOSE_ENTRY: {
1662                    SomeArgs args = (SomeArgs) msg.obj;
1663                    Uri uri = (Uri) args.arg1;
1664                    long time = (long) args.arg2;
1665                    onCloseEntry(uri, time);
1666                    args.recycle();
1667                    return;
1668                }
1669                default: {
1670                    Slog.w(TAG, "Unhandled message code: " + msg.what);
1671                    return;
1672                }
1673            }
1674        }
1675
1676        private void onOpenEntry(Uri uri, long channelId, long watchStarttime) {
1677            String[] projection = {
1678                    TvContract.Programs.COLUMN_TITLE,
1679                    TvContract.Programs.COLUMN_START_TIME_UTC_MILLIS,
1680                    TvContract.Programs.COLUMN_END_TIME_UTC_MILLIS,
1681                    TvContract.Programs.COLUMN_SHORT_DESCRIPTION
1682            };
1683            String selection = TvContract.Programs.COLUMN_CHANNEL_ID + "=? AND "
1684                    + TvContract.Programs.COLUMN_START_TIME_UTC_MILLIS + "<=? AND "
1685                    + TvContract.Programs.COLUMN_END_TIME_UTC_MILLIS + ">?";
1686            String[] selectionArgs = {
1687                    String.valueOf(channelId),
1688                    String.valueOf(watchStarttime),
1689                    String.valueOf(watchStarttime)
1690            };
1691            String sortOrder = TvContract.Programs.COLUMN_START_TIME_UTC_MILLIS + " ASC";
1692            Cursor cursor = null;
1693            try {
1694                cursor = mContentResolver.query(TvContract.Programs.CONTENT_URI, projection,
1695                        selection, selectionArgs, sortOrder);
1696                if (cursor != null && cursor.moveToNext()) {
1697                    ContentValues values = new ContentValues();
1698                    values.put(TvContract.WatchedPrograms.COLUMN_TITLE, cursor.getString(0));
1699                    values.put(TvContract.WatchedPrograms.COLUMN_START_TIME_UTC_MILLIS,
1700                            cursor.getLong(1));
1701                    long endTime = cursor.getLong(2);
1702                    values.put(TvContract.WatchedPrograms.COLUMN_END_TIME_UTC_MILLIS, endTime);
1703                    values.put(TvContract.WatchedPrograms.COLUMN_DESCRIPTION, cursor.getString(3));
1704                    mContentResolver.update(uri, values, null, null);
1705
1706                    // Schedule an update when the current program ends.
1707                    SomeArgs args = SomeArgs.obtain();
1708                    args.arg1 = uri;
1709                    args.arg2 = channelId;
1710                    args.arg3 = endTime;
1711                    Message msg = obtainMessage(LogHandler.MSG_UPDATE_ENTRY, args);
1712                    sendMessageDelayed(msg, endTime - System.currentTimeMillis());
1713                }
1714            } finally {
1715                if (cursor != null) {
1716                    cursor.close();
1717                }
1718            }
1719        }
1720
1721        private void onUpdateEntry(Uri uri, long channelId, long time) {
1722            String[] projection = {
1723                    TvContract.WatchedPrograms.COLUMN_WATCH_START_TIME_UTC_MILLIS,
1724                    TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS,
1725                    TvContract.WatchedPrograms.COLUMN_TITLE,
1726                    TvContract.WatchedPrograms.COLUMN_START_TIME_UTC_MILLIS,
1727                    TvContract.WatchedPrograms.COLUMN_END_TIME_UTC_MILLIS,
1728                    TvContract.WatchedPrograms.COLUMN_DESCRIPTION
1729            };
1730            Cursor cursor = null;
1731            try {
1732                cursor = mContentResolver.query(uri, projection, null, null, null);
1733                if (cursor != null && cursor.moveToNext()) {
1734                    long watchStartTime = cursor.getLong(0);
1735                    long watchEndTime = cursor.getLong(1);
1736                    String title = cursor.getString(2);
1737                    long startTime = cursor.getLong(3);
1738                    long endTime = cursor.getLong(4);
1739                    String description = cursor.getString(5);
1740
1741                    // Do nothing if the current log entry is already closed.
1742                    if (watchEndTime > 0) {
1743                        return;
1744                    }
1745
1746                    // The current program has just ended. Create a (complete) log entry off the
1747                    // current entry.
1748                    ContentValues values = new ContentValues();
1749                    values.put(TvContract.WatchedPrograms.COLUMN_WATCH_START_TIME_UTC_MILLIS,
1750                            watchStartTime);
1751                    values.put(TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS, time);
1752                    values.put(TvContract.WatchedPrograms.COLUMN_CHANNEL_ID, channelId);
1753                    values.put(TvContract.WatchedPrograms.COLUMN_TITLE, title);
1754                    values.put(TvContract.WatchedPrograms.COLUMN_START_TIME_UTC_MILLIS, startTime);
1755                    values.put(TvContract.WatchedPrograms.COLUMN_END_TIME_UTC_MILLIS, endTime);
1756                    values.put(TvContract.WatchedPrograms.COLUMN_DESCRIPTION, description);
1757                    mContentResolver.insert(TvContract.WatchedPrograms.CONTENT_URI, values);
1758                }
1759            } finally {
1760                if (cursor != null) {
1761                    cursor.close();
1762                }
1763            }
1764            // Re-open the current log entry with the next program information.
1765            onOpenEntry(uri, channelId, time);
1766        }
1767
1768        private void onCloseEntry(Uri uri, long watchEndTime) {
1769            ContentValues values = new ContentValues();
1770            values.put(TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS, watchEndTime);
1771            mContentResolver.update(uri, values, null, null);
1772        }
1773    }
1774
1775    final class HardwareListener implements TvInputHardwareManager.Listener {
1776        @Override
1777        public void onStateChanged(String inputId, int state) {
1778            synchronized (mLock) {
1779                setStateLocked(inputId, state, mCurrentUserId);
1780            }
1781        }
1782
1783        @Override
1784        public void onHardwareDeviceAdded(TvInputHardwareInfo info) {
1785            synchronized (mLock) {
1786                UserState userState = getUserStateLocked(mCurrentUserId);
1787                // Broadcast the event to all hardware inputs.
1788                for (ServiceState serviceState : userState.serviceStateMap.values()) {
1789                    if (!serviceState.mIsHardware || serviceState.mService == null) continue;
1790                    try {
1791                        serviceState.mService.notifyHardwareAdded(info);
1792                    } catch (RemoteException e) {
1793                        Slog.e(TAG, "error in notifyHardwareAdded", e);
1794                    }
1795                }
1796            }
1797        }
1798
1799        @Override
1800        public void onHardwareDeviceRemoved(int deviceId) {
1801            synchronized (mLock) {
1802                UserState userState = getUserStateLocked(mCurrentUserId);
1803                // Broadcast the event to all hardware inputs.
1804                for (ServiceState serviceState : userState.serviceStateMap.values()) {
1805                    if (!serviceState.mIsHardware || serviceState.mService == null) continue;
1806                    try {
1807                        serviceState.mService.notifyHardwareRemoved(deviceId);
1808                    } catch (RemoteException e) {
1809                        Slog.e(TAG, "error in notifyHardwareRemoved", e);
1810                    }
1811                }
1812            }
1813        }
1814
1815        @Override
1816        public void onHdmiCecDeviceAdded(HdmiCecDeviceInfo cecDevice) {
1817            synchronized (mLock) {
1818                // TODO
1819            }
1820        }
1821
1822        @Override
1823        public void onHdmiCecDeviceRemoved(HdmiCecDeviceInfo cecDevice) {
1824            synchronized (mLock) {
1825                // TODO
1826            }
1827        }
1828    }
1829}
1830