TvInputManagerService.java revision 4f9f57cede3de2e2aa3045e04b485b176ab22dbd
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> inputList = 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                inputList.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                        inputList.addAll(serviceState.mInputList);
244                    }
245                } else {
246                    inputList.add(TvInputInfo.createTvInputInfo(mContext, ri));
247                }
248
249                for (TvInputInfo info : inputList) {
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 onContentAllowed() {
569                synchronized (mLock) {
570                    if (DEBUG) {
571                        Slog.d(TAG, "onContentAllowed()");
572                    }
573                    if (sessionState.mSession == null || sessionState.mClient == null) {
574                        return;
575                    }
576                    try {
577                        sessionState.mClient.onContentAllowed(sessionState.mSeq);
578                    } catch (RemoteException e) {
579                        Slog.e(TAG, "error in onContentAllowed");
580                    }
581                }
582            }
583
584            @Override
585            public void onContentBlocked(String rating) {
586                synchronized (mLock) {
587                    if (DEBUG) {
588                        Slog.d(TAG, "onContentBlocked()");
589                    }
590                    if (sessionState.mSession == null || sessionState.mClient == null) {
591                        return;
592                    }
593                    try {
594                        sessionState.mClient.onContentBlocked(rating, sessionState.mSeq);
595                    } catch (RemoteException e) {
596                        Slog.e(TAG, "error in onContentBlocked");
597                    }
598                }
599            }
600
601            @Override
602            public void onSessionEvent(String eventType, Bundle eventArgs) {
603                synchronized (mLock) {
604                    if (DEBUG) {
605                        Slog.d(TAG, "onEvent(what=" + eventType + ", data=" + eventArgs + ")");
606                    }
607                    if (sessionState.mSession == null || sessionState.mClient == null) {
608                        return;
609                    }
610                    try {
611                        sessionState.mClient.onSessionEvent(eventType, eventArgs,
612                                sessionState.mSeq);
613                    } catch (RemoteException e) {
614                        Slog.e(TAG, "error in onSessionEvent");
615                    }
616                }
617            }
618        };
619
620        // Create a session. When failed, send a null token immediately.
621        try {
622            service.createSession(channels[1], callback, sessionState.mInfo.getId());
623        } catch (RemoteException e) {
624            Slog.e(TAG, "error in createSession", e);
625            removeSessionStateLocked(sessionToken, userId);
626            sendSessionTokenToClientLocked(sessionState.mClient, sessionState.mInfo.getId(), null,
627                    null, sessionState.mSeq);
628        }
629        channels[1].dispose();
630    }
631
632    private void sendSessionTokenToClientLocked(ITvInputClient client, String inputId,
633            IBinder sessionToken, InputChannel channel, int seq) {
634        try {
635            client.onSessionCreated(inputId, sessionToken, channel, seq);
636        } catch (RemoteException exception) {
637            Slog.e(TAG, "error in onSessionCreated", exception);
638        }
639    }
640
641    private void releaseSessionLocked(IBinder sessionToken, int callingUid, int userId) {
642        SessionState sessionState = getSessionStateLocked(sessionToken, callingUid, userId);
643        if (sessionState.mSession != null) {
644            try {
645                sessionState.mSession.release();
646            } catch (RemoteException e) {
647                Slog.w(TAG, "session is already disapeared", e);
648            }
649            sessionState.mSession = null;
650        }
651        removeSessionStateLocked(sessionToken, userId);
652    }
653
654    private void removeSessionStateLocked(IBinder sessionToken, int userId) {
655        // Remove the session state from the global session state map of the current user.
656        UserState userState = getUserStateLocked(userId);
657        SessionState sessionState = userState.sessionStateMap.remove(sessionToken);
658
659        // Close the open log entry, if any.
660        if (sessionState.mLogUri != null) {
661            SomeArgs args = SomeArgs.obtain();
662            args.arg1 = sessionState.mLogUri;
663            args.arg2 = System.currentTimeMillis();
664            mLogHandler.obtainMessage(LogHandler.MSG_CLOSE_ENTRY, args).sendToTarget();
665        }
666
667        // Also remove the session token from the session token list of the current client and
668        // service.
669        ClientState clientState = userState.clientStateMap.get(sessionState.mClient.asBinder());
670        if (clientState != null) {
671            clientState.mSessionTokens.remove(sessionToken);
672            if (clientState.isEmpty()) {
673                userState.clientStateMap.remove(sessionState.mClient.asBinder());
674            }
675        }
676
677        TvInputInfo info = sessionState.mInfo;
678        if (info != null) {
679            ServiceState serviceState = userState.serviceStateMap.get(info.getComponent());
680            if (serviceState != null) {
681                serviceState.mSessionTokens.remove(sessionToken);
682            }
683        }
684        updateServiceConnectionLocked(sessionState.mInfo.getComponent(), userId);
685    }
686
687    private void unregisterClientInternalLocked(IBinder clientToken, String inputId,
688            int userId) {
689        UserState userState = getUserStateLocked(userId);
690        ClientState clientState = userState.clientStateMap.get(clientToken);
691        if (clientState != null) {
692            clientState.mInputIds.remove(inputId);
693            if (clientState.isEmpty()) {
694                userState.clientStateMap.remove(clientToken);
695            }
696        }
697
698        TvInputInfo info = userState.inputMap.get(inputId).mInfo;
699        if (info == null) {
700            return;
701        }
702        ServiceState serviceState = userState.serviceStateMap.get(info.getComponent());
703        if (serviceState == null) {
704            return;
705        }
706
707        // Remove this client from the client list and unregister the callback.
708        serviceState.mClientTokens.remove(clientToken);
709        if (!serviceState.mClientTokens.isEmpty()) {
710            // We have other clients who want to keep the callback. Do this later.
711            return;
712        }
713        if (serviceState.mService == null || serviceState.mCallback == null) {
714            return;
715        }
716        try {
717            serviceState.mService.unregisterCallback(serviceState.mCallback);
718        } catch (RemoteException e) {
719            Slog.e(TAG, "error in unregisterCallback", e);
720        } finally {
721            serviceState.mCallback = null;
722            updateServiceConnectionLocked(info.getComponent(), userId);
723        }
724    }
725
726    private void notifyInputAddedLocked(UserState userState, String inputId) {
727        if (DEBUG) {
728            Slog.d(TAG, "notifyInputAdded: inputId = " + inputId);
729        }
730        for (ITvInputManagerCallback callback : userState.callbackSet) {
731            try {
732                callback.onInputAdded(inputId);
733            } catch (RemoteException e) {
734                Slog.e(TAG, "Failed to report added input to callback.");
735            }
736        }
737    }
738
739    private void notifyInputRemovedLocked(UserState userState, String inputId) {
740        if (DEBUG) {
741            Slog.d(TAG, "notifyInputRemovedLocked: inputId = " + inputId);
742        }
743        for (ITvInputManagerCallback callback : userState.callbackSet) {
744            try {
745                callback.onInputRemoved(inputId);
746            } catch (RemoteException e) {
747                Slog.e(TAG, "Failed to report removed input to callback.");
748            }
749        }
750    }
751
752    private void notifyInputStateChangedLocked(UserState userState, String inputId,
753            int state, ITvInputManagerCallback targetCallback) {
754        if (DEBUG) {
755            Slog.d(TAG, "notifyInputStateChangedLocked: inputId = " + inputId
756                    + "; state = " + state);
757        }
758        if (targetCallback == null) {
759            for (ITvInputManagerCallback callback : userState.callbackSet) {
760                try {
761                    callback.onInputStateChanged(inputId, state);
762                } catch (RemoteException e) {
763                    Slog.e(TAG, "Failed to report state change to callback.");
764                }
765            }
766        } else {
767            try {
768                targetCallback.onInputStateChanged(inputId, state);
769            } catch (RemoteException e) {
770                Slog.e(TAG, "Failed to report state change to callback.");
771            }
772        }
773    }
774
775    private void setStateLocked(String inputId, int state, int userId) {
776        UserState userState = getUserStateLocked(userId);
777        TvInputState inputState = userState.inputMap.get(inputId);
778        ServiceState serviceState = userState.serviceStateMap.get(inputId);
779        int oldState = inputState.mState;
780        inputState.mState = state;
781        if (serviceState != null && serviceState.mService == null
782                && shouldMaintainConnection(serviceState)) {
783            // We don't notify state change while reconnecting. It should remain disconnected.
784            return;
785        }
786        if (oldState != state) {
787            notifyInputStateChangedLocked(userState, inputId, state, null);
788        }
789    }
790
791    private final class BinderService extends ITvInputManager.Stub {
792        @Override
793        public List<TvInputInfo> getTvInputList(int userId) {
794            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(),
795                    Binder.getCallingUid(), userId, "getTvInputList");
796            final long identity = Binder.clearCallingIdentity();
797            try {
798                synchronized (mLock) {
799                    UserState userState = getUserStateLocked(resolvedUserId);
800                    List<TvInputInfo> inputList = new ArrayList<TvInputInfo>();
801                    for (TvInputState state : userState.inputMap.values()) {
802                        inputList.add(state.mInfo);
803                    }
804                    return inputList;
805                }
806            } finally {
807                Binder.restoreCallingIdentity(identity);
808            }
809        }
810
811        @Override
812        public TvInputInfo getTvInputInfo(String inputId, int userId) {
813            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(),
814                    Binder.getCallingUid(), userId, "getTvInputInfo");
815            final long identity = Binder.clearCallingIdentity();
816            try {
817                synchronized (mLock) {
818                    UserState userState = getUserStateLocked(resolvedUserId);
819                    TvInputState state = userState.inputMap.get(inputId);
820                    return state == null ? null : state.mInfo;
821                }
822            } finally {
823                Binder.restoreCallingIdentity(identity);
824            }
825        }
826
827        @Override
828        public void registerCallback(final ITvInputManagerCallback callback, int userId) {
829            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(),
830                    Binder.getCallingUid(), userId, "registerCallback");
831            final long identity = Binder.clearCallingIdentity();
832            try {
833                synchronized (mLock) {
834                    UserState userState = getUserStateLocked(resolvedUserId);
835                    userState.callbackSet.add(callback);
836                    for (TvInputState state : userState.inputMap.values()) {
837                        notifyInputStateChangedLocked(userState, state.mInfo.getId(),
838                                state.mState, callback);
839                    }
840                }
841            } finally {
842                Binder.restoreCallingIdentity(identity);
843            }
844        }
845
846        @Override
847        public void unregisterCallback(ITvInputManagerCallback callback, int userId) {
848            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(),
849                    Binder.getCallingUid(), userId, "unregisterCallback");
850            final long identity = Binder.clearCallingIdentity();
851            try {
852                synchronized (mLock) {
853                    UserState userState = getUserStateLocked(resolvedUserId);
854                    userState.callbackSet.remove(callback);
855                }
856            } finally {
857                Binder.restoreCallingIdentity(identity);
858            }
859        }
860
861        @Override
862        public void createSession(final ITvInputClient client, final String inputId,
863                int seq, int userId) {
864            final int callingUid = Binder.getCallingUid();
865            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
866                    userId, "createSession");
867            final long identity = Binder.clearCallingIdentity();
868            try {
869                synchronized (mLock) {
870                    UserState userState = getUserStateLocked(resolvedUserId);
871                    TvInputInfo info = userState.inputMap.get(inputId).mInfo;
872                    ServiceState serviceState = userState.serviceStateMap.get(info.getComponent());
873                    if (serviceState == null) {
874                        serviceState = new ServiceState(info.getComponent(), resolvedUserId);
875                        userState.serviceStateMap.put(info.getComponent(), serviceState);
876                    }
877                    // Send a null token immediately while reconnecting.
878                    if (serviceState.mReconnecting == true) {
879                        sendSessionTokenToClientLocked(client, inputId, null, null, seq);
880                        return;
881                    }
882
883                    // Create a new session token and a session state.
884                    IBinder sessionToken = new Binder();
885                    SessionState sessionState = new SessionState(sessionToken, info, client,
886                            seq, callingUid, resolvedUserId);
887
888                    // Add them to the global session state map of the current user.
889                    userState.sessionStateMap.put(sessionToken, sessionState);
890
891                    // Also, add them to the session state map of the current service.
892                    serviceState.mSessionTokens.add(sessionToken);
893
894                    if (serviceState.mService != null) {
895                        createSessionInternalLocked(serviceState.mService, sessionToken,
896                                resolvedUserId);
897                    } else {
898                        updateServiceConnectionLocked(info.getComponent(), resolvedUserId);
899                    }
900                }
901            } finally {
902                Binder.restoreCallingIdentity(identity);
903            }
904        }
905
906        @Override
907        public void releaseSession(IBinder sessionToken, int userId) {
908            final int callingUid = Binder.getCallingUid();
909            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
910                    userId, "releaseSession");
911            final long identity = Binder.clearCallingIdentity();
912            try {
913                synchronized (mLock) {
914                    releaseSessionLocked(sessionToken, callingUid, resolvedUserId);
915                }
916            } finally {
917                Binder.restoreCallingIdentity(identity);
918            }
919        }
920
921        @Override
922        public void setSurface(IBinder sessionToken, Surface surface, int userId) {
923            final int callingUid = Binder.getCallingUid();
924            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
925                    userId, "setSurface");
926            final long identity = Binder.clearCallingIdentity();
927            try {
928                synchronized (mLock) {
929                    try {
930                        getSessionLocked(sessionToken, callingUid, resolvedUserId).setSurface(
931                                surface);
932                    } catch (RemoteException e) {
933                        Slog.e(TAG, "error in setSurface", e);
934                    }
935                }
936            } finally {
937                if (surface != null) {
938                    // surface is not used in TvInputManagerService.
939                    surface.release();
940                }
941                Binder.restoreCallingIdentity(identity);
942            }
943        }
944
945        @Override
946        public void dispatchSurfaceChanged(IBinder sessionToken, int format, int width,
947                int height, int userId) {
948            final int callingUid = Binder.getCallingUid();
949            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
950                    userId, "dispatchSurfaceChanged");
951            final long identity = Binder.clearCallingIdentity();
952            try {
953                synchronized (mLock) {
954                    try {
955                        getSessionLocked(sessionToken, callingUid, resolvedUserId)
956                                .dispatchSurfaceChanged(format, width, height);
957                    } catch (RemoteException e) {
958                        Slog.e(TAG, "error in dispatchSurfaceChanged", e);
959                    }
960                }
961            } finally {
962                Binder.restoreCallingIdentity(identity);
963            }
964        }
965
966        @Override
967        public void setVolume(IBinder sessionToken, float volume, int userId) {
968            final int callingUid = Binder.getCallingUid();
969            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
970                    userId, "setVolume");
971            final long identity = Binder.clearCallingIdentity();
972            try {
973                synchronized (mLock) {
974                    try {
975                        getSessionLocked(sessionToken, callingUid, resolvedUserId).setVolume(
976                                volume);
977                    } catch (RemoteException e) {
978                        Slog.e(TAG, "error in setVolume", e);
979                    }
980                }
981            } finally {
982                Binder.restoreCallingIdentity(identity);
983            }
984        }
985
986        @Override
987        public void tune(IBinder sessionToken, final Uri channelUri, int userId) {
988            final int callingUid = Binder.getCallingUid();
989            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
990                    userId, "tune");
991            final long identity = Binder.clearCallingIdentity();
992            try {
993                synchronized (mLock) {
994                    try {
995                        getSessionLocked(sessionToken, callingUid, resolvedUserId).tune(channelUri);
996
997                        long currentTime = System.currentTimeMillis();
998                        long channelId = ContentUris.parseId(channelUri);
999
1000                        // Close the open log entry first, if any.
1001                        UserState userState = getUserStateLocked(resolvedUserId);
1002                        SessionState sessionState = userState.sessionStateMap.get(sessionToken);
1003                        if (sessionState.mLogUri != null) {
1004                            SomeArgs args = SomeArgs.obtain();
1005                            args.arg1 = sessionState.mLogUri;
1006                            args.arg2 = currentTime;
1007                            mLogHandler.obtainMessage(LogHandler.MSG_CLOSE_ENTRY, args)
1008                                    .sendToTarget();
1009                        }
1010
1011                        // Create a log entry and fill it later.
1012                        String packageName = sessionState.mInfo.getServiceInfo().packageName;
1013                        ContentValues values = new ContentValues();
1014                        values.put(TvContract.WatchedPrograms.COLUMN_PACKAGE_NAME, packageName);
1015                        values.put(TvContract.WatchedPrograms.COLUMN_WATCH_START_TIME_UTC_MILLIS,
1016                                currentTime);
1017                        values.put(TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS, 0);
1018                        values.put(TvContract.WatchedPrograms.COLUMN_CHANNEL_ID, channelId);
1019
1020                        sessionState.mLogUri = mContentResolver.insert(
1021                                TvContract.WatchedPrograms.CONTENT_URI, values);
1022                        SomeArgs args = SomeArgs.obtain();
1023                        args.arg1 = sessionState.mLogUri;
1024                        args.arg2 = ContentUris.parseId(channelUri);
1025                        args.arg3 = currentTime;
1026                        mLogHandler.obtainMessage(LogHandler.MSG_OPEN_ENTRY, args).sendToTarget();
1027                    } catch (RemoteException e) {
1028                        Slog.e(TAG, "error in tune", e);
1029                        return;
1030                    }
1031                }
1032            } finally {
1033                Binder.restoreCallingIdentity(identity);
1034            }
1035        }
1036
1037        @Override
1038        public void requestUnblockContent(
1039                IBinder sessionToken, String unblockedRating, int userId) {
1040            final int callingUid = Binder.getCallingUid();
1041            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1042                    userId, "unblockContent");
1043            final long identity = Binder.clearCallingIdentity();
1044            try {
1045                synchronized (mLock) {
1046                    try {
1047                        getSessionLocked(sessionToken, callingUid, resolvedUserId)
1048                                .requestUnblockContent(unblockedRating);
1049                    } catch (RemoteException e) {
1050                        Slog.e(TAG, "error in unblockContent", e);
1051                    }
1052                }
1053            } finally {
1054                Binder.restoreCallingIdentity(identity);
1055            }
1056        }
1057
1058        @Override
1059        public void setCaptionEnabled(IBinder sessionToken, boolean enabled, int userId) {
1060            final int callingUid = Binder.getCallingUid();
1061            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1062                    userId, "setCaptionEnabled");
1063            final long identity = Binder.clearCallingIdentity();
1064            try {
1065                synchronized (mLock) {
1066                    try {
1067                        getSessionLocked(sessionToken, callingUid, resolvedUserId)
1068                                .setCaptionEnabled(enabled);
1069                    } catch (RemoteException e) {
1070                        Slog.e(TAG, "error in setCaptionEnabled", e);
1071                    }
1072                }
1073            } finally {
1074                Binder.restoreCallingIdentity(identity);
1075            }
1076        }
1077
1078        @Override
1079        public void selectTrack(IBinder sessionToken, TvTrackInfo track, int userId) {
1080            final int callingUid = Binder.getCallingUid();
1081            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1082                    userId, "selectTrack");
1083            final long identity = Binder.clearCallingIdentity();
1084            try {
1085                synchronized (mLock) {
1086                    try {
1087                        getSessionLocked(sessionToken, callingUid, resolvedUserId).selectTrack(
1088                                track);
1089                    } catch (RemoteException e) {
1090                        Slog.e(TAG, "error in selectTrack", e);
1091                    }
1092                }
1093            } finally {
1094                Binder.restoreCallingIdentity(identity);
1095            }
1096        }
1097
1098        @Override
1099        public void unselectTrack(IBinder sessionToken, TvTrackInfo track, int userId) {
1100            final int callingUid = Binder.getCallingUid();
1101            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1102                    userId, "unselectTrack");
1103            final long identity = Binder.clearCallingIdentity();
1104            try {
1105                synchronized (mLock) {
1106                    try {
1107                        getSessionLocked(sessionToken, callingUid, resolvedUserId).unselectTrack(
1108                                track);
1109                    } catch (RemoteException e) {
1110                        Slog.e(TAG, "error in unselectTrack", e);
1111                    }
1112                }
1113            } finally {
1114                Binder.restoreCallingIdentity(identity);
1115            }
1116        }
1117
1118        @Override
1119        public void sendAppPrivateCommand(IBinder sessionToken, String command, Bundle data,
1120                int userId) {
1121            final int callingUid = Binder.getCallingUid();
1122            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1123                    userId, "sendAppPrivateCommand");
1124            final long identity = Binder.clearCallingIdentity();
1125            try {
1126                synchronized (mLock) {
1127                    try {
1128                        getSessionLocked(sessionToken, callingUid, resolvedUserId)
1129                                .appPrivateCommand(command, data);
1130                    } catch (RemoteException e) {
1131                        Slog.e(TAG, "error in sendAppPrivateCommand", e);
1132                    }
1133                }
1134            } finally {
1135                Binder.restoreCallingIdentity(identity);
1136            }
1137        }
1138
1139        @Override
1140        public void createOverlayView(IBinder sessionToken, IBinder windowToken, Rect frame,
1141                int userId) {
1142            final int callingUid = Binder.getCallingUid();
1143            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1144                    userId, "createOverlayView");
1145            final long identity = Binder.clearCallingIdentity();
1146            try {
1147                synchronized (mLock) {
1148                    try {
1149                        getSessionLocked(sessionToken, callingUid, resolvedUserId)
1150                                .createOverlayView(windowToken, frame);
1151                    } catch (RemoteException e) {
1152                        Slog.e(TAG, "error in createOverlayView", e);
1153                    }
1154                }
1155            } finally {
1156                Binder.restoreCallingIdentity(identity);
1157            }
1158        }
1159
1160        @Override
1161        public void relayoutOverlayView(IBinder sessionToken, Rect frame, int userId) {
1162            final int callingUid = Binder.getCallingUid();
1163            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1164                    userId, "relayoutOverlayView");
1165            final long identity = Binder.clearCallingIdentity();
1166            try {
1167                synchronized (mLock) {
1168                    try {
1169                        getSessionLocked(sessionToken, callingUid, resolvedUserId)
1170                                .relayoutOverlayView(frame);
1171                    } catch (RemoteException e) {
1172                        Slog.e(TAG, "error in relayoutOverlayView", e);
1173                    }
1174                }
1175            } finally {
1176                Binder.restoreCallingIdentity(identity);
1177            }
1178        }
1179
1180        @Override
1181        public void removeOverlayView(IBinder sessionToken, int userId) {
1182            final int callingUid = Binder.getCallingUid();
1183            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1184                    userId, "removeOverlayView");
1185            final long identity = Binder.clearCallingIdentity();
1186            try {
1187                synchronized (mLock) {
1188                    try {
1189                        getSessionLocked(sessionToken, callingUid, resolvedUserId)
1190                                .removeOverlayView();
1191                    } catch (RemoteException e) {
1192                        Slog.e(TAG, "error in removeOverlayView", e);
1193                    }
1194                }
1195            } finally {
1196                Binder.restoreCallingIdentity(identity);
1197            }
1198        }
1199
1200        @Override
1201        public List<TvInputHardwareInfo> getHardwareList() throws RemoteException {
1202            if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1203                    != PackageManager.PERMISSION_GRANTED) {
1204                return null;
1205            }
1206
1207            final long identity = Binder.clearCallingIdentity();
1208            try {
1209                return mTvInputHardwareManager.getHardwareList();
1210            } finally {
1211                Binder.restoreCallingIdentity(identity);
1212            }
1213        }
1214
1215        @Override
1216        public ITvInputHardware acquireTvInputHardware(int deviceId,
1217                ITvInputHardwareCallback callback, TvInputInfo info, int userId)
1218                throws RemoteException {
1219            if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1220                    != PackageManager.PERMISSION_GRANTED) {
1221                return null;
1222            }
1223
1224            final long identity = Binder.clearCallingIdentity();
1225            final int callingUid = Binder.getCallingUid();
1226            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1227                    userId, "acquireTvInputHardware");
1228            try {
1229                return mTvInputHardwareManager.acquireHardware(
1230                        deviceId, callback, info, callingUid, resolvedUserId);
1231            } finally {
1232                Binder.restoreCallingIdentity(identity);
1233            }
1234        }
1235
1236        @Override
1237        public void releaseTvInputHardware(int deviceId, ITvInputHardware hardware, int userId)
1238                throws RemoteException {
1239            if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1240                    != PackageManager.PERMISSION_GRANTED) {
1241                return;
1242            }
1243
1244            final long identity = Binder.clearCallingIdentity();
1245            final int callingUid = Binder.getCallingUid();
1246            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1247                    userId, "releaseTvInputHardware");
1248            try {
1249                mTvInputHardwareManager.releaseHardware(
1250                        deviceId, hardware, callingUid, resolvedUserId);
1251            } finally {
1252                Binder.restoreCallingIdentity(identity);
1253            }
1254        }
1255
1256        @Override
1257        @SuppressWarnings("resource")
1258        protected void dump(FileDescriptor fd, final PrintWriter writer, String[] args) {
1259            final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
1260            if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1261                    != PackageManager.PERMISSION_GRANTED) {
1262                pw.println("Permission Denial: can't dump TvInputManager from pid="
1263                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
1264                return;
1265            }
1266
1267            synchronized (mLock) {
1268                pw.println("User Ids (Current user: " + mCurrentUserId + "):");
1269                pw.increaseIndent();
1270                for (int i = 0; i < mUserStates.size(); i++) {
1271                    int userId = mUserStates.keyAt(i);
1272                    pw.println(Integer.valueOf(userId));
1273                }
1274                pw.decreaseIndent();
1275
1276                for (int i = 0; i < mUserStates.size(); i++) {
1277                    int userId = mUserStates.keyAt(i);
1278                    UserState userState = getUserStateLocked(userId);
1279                    pw.println("UserState (" + userId + "):");
1280                    pw.increaseIndent();
1281
1282                    pw.println("inputMap: inputId -> TvInputState");
1283                    pw.increaseIndent();
1284                    for (Map.Entry<String, TvInputState> entry: userState.inputMap.entrySet()) {
1285                        pw.println(entry.getKey() + ": " + entry.getValue());
1286                    }
1287                    pw.decreaseIndent();
1288
1289                    pw.println("packageSet:");
1290                    pw.increaseIndent();
1291                    for (String packageName : userState.packageSet) {
1292                        pw.println(packageName);
1293                    }
1294                    pw.decreaseIndent();
1295
1296                    pw.println("clientStateMap: ITvInputClient -> ClientState");
1297                    pw.increaseIndent();
1298                    for (Map.Entry<IBinder, ClientState> entry :
1299                            userState.clientStateMap.entrySet()) {
1300                        ClientState client = entry.getValue();
1301                        pw.println(entry.getKey() + ": " + client);
1302
1303                        pw.increaseIndent();
1304
1305                        pw.println("mInputIds:");
1306                        pw.increaseIndent();
1307                        for (String inputId : client.mInputIds) {
1308                            pw.println(inputId);
1309                        }
1310                        pw.decreaseIndent();
1311
1312                        pw.println("mSessionTokens:");
1313                        pw.increaseIndent();
1314                        for (IBinder token : client.mSessionTokens) {
1315                            pw.println("" + token);
1316                        }
1317                        pw.decreaseIndent();
1318
1319                        pw.println("mClientTokens: " + client.mClientToken);
1320                        pw.println("mUserId: " + client.mUserId);
1321
1322                        pw.decreaseIndent();
1323                    }
1324                    pw.decreaseIndent();
1325
1326                    pw.println("serviceStateMap: ComponentName -> ServiceState");
1327                    pw.increaseIndent();
1328                    for (Map.Entry<ComponentName, ServiceState> entry :
1329                            userState.serviceStateMap.entrySet()) {
1330                        ServiceState service = entry.getValue();
1331                        pw.println(entry.getKey() + ": " + service);
1332
1333                        pw.increaseIndent();
1334
1335                        pw.println("mClientTokens:");
1336                        pw.increaseIndent();
1337                        for (IBinder token : service.mClientTokens) {
1338                            pw.println("" + token);
1339                        }
1340                        pw.decreaseIndent();
1341
1342                        pw.println("mSessionTokens:");
1343                        pw.increaseIndent();
1344                        for (IBinder token : service.mSessionTokens) {
1345                            pw.println("" + token);
1346                        }
1347                        pw.decreaseIndent();
1348
1349                        pw.println("mService: " + service.mService);
1350                        pw.println("mCallback: " + service.mCallback);
1351                        pw.println("mBound: " + service.mBound);
1352                        pw.println("mReconnecting: " + service.mReconnecting);
1353
1354                        pw.decreaseIndent();
1355                    }
1356                    pw.decreaseIndent();
1357
1358                    pw.println("sessionStateMap: ITvInputSession -> SessionState");
1359                    pw.increaseIndent();
1360                    for (Map.Entry<IBinder, SessionState> entry :
1361                            userState.sessionStateMap.entrySet()) {
1362                        SessionState session = entry.getValue();
1363                        pw.println(entry.getKey() + ": " + session);
1364
1365                        pw.increaseIndent();
1366                        pw.println("mInfo: " + session.mInfo);
1367                        pw.println("mClient: " + session.mClient);
1368                        pw.println("mSeq: " + session.mSeq);
1369                        pw.println("mCallingUid: " + session.mCallingUid);
1370                        pw.println("mUserId: " + session.mUserId);
1371                        pw.println("mSessionToken: " + session.mSessionToken);
1372                        pw.println("mSession: " + session.mSession);
1373                        pw.println("mLogUri: " + session.mLogUri);
1374                        pw.decreaseIndent();
1375                    }
1376                    pw.decreaseIndent();
1377
1378                    pw.println("callbackSet:");
1379                    pw.increaseIndent();
1380                    for (ITvInputManagerCallback callback : userState.callbackSet) {
1381                        pw.println(callback.toString());
1382                    }
1383                    pw.decreaseIndent();
1384
1385                    pw.decreaseIndent();
1386                }
1387            }
1388        }
1389    }
1390
1391    private static final class TvInputState {
1392        // A TvInputInfo object which represents the TV input.
1393        private TvInputInfo mInfo;
1394
1395        // The state of TV input. Connected by default.
1396        private int mState = INPUT_STATE_CONNECTED;
1397
1398        @Override
1399        public String toString() {
1400            return "mInfo: " + mInfo + "; mState: " + mState;
1401        }
1402    }
1403
1404    private static final class UserState {
1405        // A mapping from the TV input id to its TvInputState.
1406        private Map<String, TvInputState> inputMap = new HashMap<String, TvInputState>();
1407
1408        // A set of all TV input packages.
1409        private final Set<String> packageSet = new HashSet<String>();
1410
1411        // A mapping from the token of a client to its state.
1412        private final Map<IBinder, ClientState> clientStateMap =
1413                new HashMap<IBinder, ClientState>();
1414
1415        // A mapping from the name of a TV input service to its state.
1416        private final Map<ComponentName, ServiceState> serviceStateMap =
1417                new HashMap<ComponentName, ServiceState>();
1418
1419        // A mapping from the token of a TV input session to its state.
1420        private final Map<IBinder, SessionState> sessionStateMap =
1421                new HashMap<IBinder, SessionState>();
1422
1423        // A set of callbacks.
1424        private final Set<ITvInputManagerCallback> callbackSet =
1425                new HashSet<ITvInputManagerCallback>();
1426    }
1427
1428    private final class ClientState implements IBinder.DeathRecipient {
1429        private final List<String> mInputIds = new ArrayList<String>();
1430        private final List<IBinder> mSessionTokens = new ArrayList<IBinder>();
1431
1432        private IBinder mClientToken;
1433        private final int mUserId;
1434
1435        ClientState(IBinder clientToken, int userId) {
1436            mClientToken = clientToken;
1437            mUserId = userId;
1438        }
1439
1440        public boolean isEmpty() {
1441            return mInputIds.isEmpty() && mSessionTokens.isEmpty();
1442        }
1443
1444        @Override
1445        public void binderDied() {
1446            synchronized (mLock) {
1447                UserState userState = getUserStateLocked(mUserId);
1448                // DO NOT remove the client state of clientStateMap in this method. It will be
1449                // removed in releaseSessionLocked() or unregisterClientInternalLocked().
1450                ClientState clientState = userState.clientStateMap.get(mClientToken);
1451                if (clientState != null) {
1452                    while (clientState.mSessionTokens.size() > 0) {
1453                        releaseSessionLocked(
1454                                clientState.mSessionTokens.get(0), Process.SYSTEM_UID, mUserId);
1455                    }
1456                    while (clientState.mInputIds.size() > 0) {
1457                        unregisterClientInternalLocked(
1458                                mClientToken, clientState.mInputIds.get(0), mUserId);
1459                    }
1460                }
1461                mClientToken = null;
1462            }
1463        }
1464    }
1465
1466    private final class ServiceState {
1467        private final List<IBinder> mClientTokens = new ArrayList<IBinder>();
1468        private final List<IBinder> mSessionTokens = new ArrayList<IBinder>();
1469        private final ServiceConnection mConnection;
1470        private final ComponentName mName;
1471        private final boolean mIsHardware;
1472        private final List<TvInputInfo> mInputList = new ArrayList<TvInputInfo>();
1473
1474        private ITvInputService mService;
1475        private ServiceCallback mCallback;
1476        private boolean mBound;
1477        private boolean mReconnecting;
1478
1479        private ServiceState(ComponentName name, int userId) {
1480            mName = name;
1481            mConnection = new InputServiceConnection(name, userId);
1482            mIsHardware = hasHardwarePermission(mContext.getPackageManager(), mName);
1483        }
1484    }
1485
1486    private final class SessionState implements IBinder.DeathRecipient {
1487        private final TvInputInfo mInfo;
1488        private final ITvInputClient mClient;
1489        private final int mSeq;
1490        private final int mCallingUid;
1491        private final int mUserId;
1492        private final IBinder mSessionToken;
1493        private ITvInputSession mSession;
1494        private Uri mLogUri;
1495
1496        private SessionState(IBinder sessionToken, TvInputInfo info, ITvInputClient client, int seq,
1497                int callingUid, int userId) {
1498            mSessionToken = sessionToken;
1499            mInfo = info;
1500            mClient = client;
1501            mSeq = seq;
1502            mCallingUid = callingUid;
1503            mUserId = userId;
1504        }
1505
1506        @Override
1507        public void binderDied() {
1508            synchronized (mLock) {
1509                mSession = null;
1510                if (mClient != null) {
1511                    try {
1512                        mClient.onSessionReleased(mSeq);
1513                    } catch(RemoteException e) {
1514                        Slog.e(TAG, "error in onSessionReleased", e);
1515                    }
1516                }
1517                removeSessionStateLocked(mSessionToken, mUserId);
1518            }
1519        }
1520    }
1521
1522    private final class InputServiceConnection implements ServiceConnection {
1523        private final ComponentName mName;
1524        private final int mUserId;
1525
1526        private InputServiceConnection(ComponentName name, int userId) {
1527            mName = name;
1528            mUserId = userId;
1529        }
1530
1531        @Override
1532        public void onServiceConnected(ComponentName name, IBinder service) {
1533            if (DEBUG) {
1534                Slog.d(TAG, "onServiceConnected(name=" + name + ")");
1535            }
1536            synchronized (mLock) {
1537                UserState userState = getUserStateLocked(mUserId);
1538                ServiceState serviceState = userState.serviceStateMap.get(mName);
1539                serviceState.mService = ITvInputService.Stub.asInterface(service);
1540
1541                // Register a callback, if we need to.
1542                if (serviceState.mIsHardware && serviceState.mCallback == null) {
1543                    serviceState.mCallback = new ServiceCallback(mName, mUserId);
1544                    try {
1545                        serviceState.mService.registerCallback(serviceState.mCallback);
1546                    } catch (RemoteException e) {
1547                        Slog.e(TAG, "error in registerCallback", e);
1548                    }
1549                }
1550
1551                // And create sessions, if any.
1552                for (IBinder sessionToken : serviceState.mSessionTokens) {
1553                    createSessionInternalLocked(serviceState.mService, sessionToken, mUserId);
1554                }
1555
1556                for (TvInputState inputState : userState.inputMap.values()) {
1557                    if (inputState.mInfo.getComponent().equals(name)
1558                            && inputState.mState != INPUT_STATE_DISCONNECTED) {
1559                        notifyInputStateChangedLocked(userState, inputState.mInfo.getId(),
1560                                inputState.mState, null);
1561                    }
1562                }
1563
1564                if (serviceState.mIsHardware) {
1565                    List<TvInputHardwareInfo> hardwareInfoList =
1566                            mTvInputHardwareManager.getHardwareList();
1567                    for (TvInputHardwareInfo hardwareInfo : hardwareInfoList) {
1568                        try {
1569                            serviceState.mService.notifyHardwareAdded(hardwareInfo);
1570                        } catch (RemoteException e) {
1571                            Slog.e(TAG, "error in notifyHardwareAdded", e);
1572                        }
1573                    }
1574
1575                    List<HdmiCecDeviceInfo> cecDeviceInfoList =
1576                            mTvInputHardwareManager.getHdmiCecInputDeviceList();
1577                    for (HdmiCecDeviceInfo cecDeviceInfo : cecDeviceInfoList) {
1578                        try {
1579                            serviceState.mService.notifyHdmiCecDeviceAdded(cecDeviceInfo);
1580                        } catch (RemoteException e) {
1581                            Slog.e(TAG, "error in notifyHdmiCecDeviceAdded", e);
1582                        }
1583                    }
1584                }
1585            }
1586        }
1587
1588        @Override
1589        public void onServiceDisconnected(ComponentName name) {
1590            if (DEBUG) {
1591                Slog.d(TAG, "onServiceDisconnected(name=" + name + ")");
1592            }
1593            if (!mName.equals(name)) {
1594                throw new IllegalArgumentException("Mismatched ComponentName: "
1595                        + mName + " (expected), " + name + " (actual).");
1596            }
1597            synchronized (mLock) {
1598                UserState userState = getUserStateLocked(mUserId);
1599                ServiceState serviceState = userState.serviceStateMap.get(mName);
1600                if (serviceState != null) {
1601                    serviceState.mReconnecting = true;
1602                    serviceState.mBound = false;
1603                    serviceState.mService = null;
1604                    serviceState.mCallback = null;
1605
1606                    // Send null tokens for not finishing create session events.
1607                    for (IBinder sessionToken : serviceState.mSessionTokens) {
1608                        SessionState sessionState = userState.sessionStateMap.get(sessionToken);
1609                        if (sessionState.mSession == null) {
1610                            removeSessionStateLocked(sessionToken, sessionState.mUserId);
1611                            sendSessionTokenToClientLocked(sessionState.mClient,
1612                                    sessionState.mInfo.getId(), null, null, sessionState.mSeq);
1613                        }
1614                    }
1615
1616                    for (TvInputState inputState : userState.inputMap.values()) {
1617                        if (inputState.mInfo.getComponent().equals(name)) {
1618                            notifyInputStateChangedLocked(userState, inputState.mInfo.getId(),
1619                                    INPUT_STATE_DISCONNECTED, null);
1620                        }
1621                    }
1622                    updateServiceConnectionLocked(mName, mUserId);
1623                }
1624            }
1625        }
1626    }
1627
1628    private final class ServiceCallback extends ITvInputServiceCallback.Stub {
1629        private final ComponentName mName;
1630        private final int mUserId;
1631
1632        ServiceCallback(ComponentName name, int userId) {
1633            mName = name;
1634            mUserId = userId;
1635        }
1636
1637        private void ensureHardwarePermission() {
1638            if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1639                    != PackageManager.PERMISSION_GRANTED) {
1640                throw new SecurityException("The caller does not have hardware permission");
1641            }
1642        }
1643
1644        private void ensureValidInput(TvInputInfo inputInfo) {
1645            if (inputInfo.getId() == null || !mName.equals(inputInfo.getComponent())) {
1646                throw new IllegalArgumentException("Invalid TvInputInfo");
1647            }
1648        }
1649
1650        private void addTvInputLocked(TvInputInfo inputInfo) {
1651            ServiceState serviceState = getServiceStateLocked(mName, mUserId);
1652            serviceState.mInputList.add(inputInfo);
1653            buildTvInputListLocked(mUserId);
1654        }
1655
1656        @Override
1657        public void addHardwareTvInput(int deviceId, TvInputInfo inputInfo) {
1658            ensureHardwarePermission();
1659            ensureValidInput(inputInfo);
1660            synchronized (mLock) {
1661                mTvInputHardwareManager.addHardwareTvInput(deviceId, inputInfo);
1662                addTvInputLocked(inputInfo);
1663            }
1664        }
1665
1666        @Override
1667        public void addHdmiCecTvInput(int logicalAddress, TvInputInfo inputInfo) {
1668            ensureHardwarePermission();
1669            ensureValidInput(inputInfo);
1670            synchronized (mLock) {
1671                mTvInputHardwareManager.addHdmiCecTvInput(logicalAddress, inputInfo);
1672                addTvInputLocked(inputInfo);
1673            }
1674        }
1675
1676        @Override
1677        public void removeTvInput(String inputId) {
1678            ensureHardwarePermission();
1679            synchronized (mLock) {
1680                ServiceState serviceState = getServiceStateLocked(mName, mUserId);
1681                boolean removed = false;
1682                for (Iterator<TvInputInfo> it = serviceState.mInputList.iterator();
1683                        it.hasNext(); ) {
1684                    if (it.next().getId().equals(inputId)) {
1685                        it.remove();
1686                        removed = true;
1687                        break;
1688                    }
1689                }
1690                if (removed) {
1691                    buildTvInputListLocked(mUserId);
1692                    mTvInputHardwareManager.removeTvInput(inputId);
1693                } else {
1694                    Slog.e(TAG, "TvInputInfo with inputId=" + inputId + " not found.");
1695                }
1696            }
1697        }
1698    }
1699
1700    private final class LogHandler extends Handler {
1701        private static final int MSG_OPEN_ENTRY = 1;
1702        private static final int MSG_UPDATE_ENTRY = 2;
1703        private static final int MSG_CLOSE_ENTRY = 3;
1704
1705        public LogHandler(Looper looper) {
1706            super(looper);
1707        }
1708
1709        @Override
1710        public void handleMessage(Message msg) {
1711            switch (msg.what) {
1712                case MSG_OPEN_ENTRY: {
1713                    SomeArgs args = (SomeArgs) msg.obj;
1714                    Uri uri = (Uri) args.arg1;
1715                    long channelId = (long) args.arg2;
1716                    long time = (long) args.arg3;
1717                    onOpenEntry(uri, channelId, time);
1718                    args.recycle();
1719                    return;
1720                }
1721                case MSG_UPDATE_ENTRY: {
1722                    SomeArgs args = (SomeArgs) msg.obj;
1723                    Uri uri = (Uri) args.arg1;
1724                    long channelId = (long) args.arg2;
1725                    long time = (long) args.arg3;
1726                    onUpdateEntry(uri, channelId, time);
1727                    args.recycle();
1728                    return;
1729                }
1730                case MSG_CLOSE_ENTRY: {
1731                    SomeArgs args = (SomeArgs) msg.obj;
1732                    Uri uri = (Uri) args.arg1;
1733                    long time = (long) args.arg2;
1734                    onCloseEntry(uri, time);
1735                    args.recycle();
1736                    return;
1737                }
1738                default: {
1739                    Slog.w(TAG, "Unhandled message code: " + msg.what);
1740                    return;
1741                }
1742            }
1743        }
1744
1745        private void onOpenEntry(Uri uri, long channelId, long watchStarttime) {
1746            String[] projection = {
1747                    TvContract.Programs.COLUMN_TITLE,
1748                    TvContract.Programs.COLUMN_START_TIME_UTC_MILLIS,
1749                    TvContract.Programs.COLUMN_END_TIME_UTC_MILLIS,
1750                    TvContract.Programs.COLUMN_SHORT_DESCRIPTION
1751            };
1752            String selection = TvContract.Programs.COLUMN_CHANNEL_ID + "=? AND "
1753                    + TvContract.Programs.COLUMN_START_TIME_UTC_MILLIS + "<=? AND "
1754                    + TvContract.Programs.COLUMN_END_TIME_UTC_MILLIS + ">?";
1755            String[] selectionArgs = {
1756                    String.valueOf(channelId),
1757                    String.valueOf(watchStarttime),
1758                    String.valueOf(watchStarttime)
1759            };
1760            String sortOrder = TvContract.Programs.COLUMN_START_TIME_UTC_MILLIS + " ASC";
1761            Cursor cursor = null;
1762            try {
1763                cursor = mContentResolver.query(TvContract.Programs.CONTENT_URI, projection,
1764                        selection, selectionArgs, sortOrder);
1765                if (cursor != null && cursor.moveToNext()) {
1766                    ContentValues values = new ContentValues();
1767                    values.put(TvContract.WatchedPrograms.COLUMN_TITLE, cursor.getString(0));
1768                    values.put(TvContract.WatchedPrograms.COLUMN_START_TIME_UTC_MILLIS,
1769                            cursor.getLong(1));
1770                    long endTime = cursor.getLong(2);
1771                    values.put(TvContract.WatchedPrograms.COLUMN_END_TIME_UTC_MILLIS, endTime);
1772                    values.put(TvContract.WatchedPrograms.COLUMN_DESCRIPTION, cursor.getString(3));
1773                    mContentResolver.update(uri, values, null, null);
1774
1775                    // Schedule an update when the current program ends.
1776                    SomeArgs args = SomeArgs.obtain();
1777                    args.arg1 = uri;
1778                    args.arg2 = channelId;
1779                    args.arg3 = endTime;
1780                    Message msg = obtainMessage(LogHandler.MSG_UPDATE_ENTRY, args);
1781                    sendMessageDelayed(msg, endTime - System.currentTimeMillis());
1782                }
1783            } finally {
1784                if (cursor != null) {
1785                    cursor.close();
1786                }
1787            }
1788        }
1789
1790        private void onUpdateEntry(Uri uri, long channelId, long time) {
1791            String[] projection = {
1792                    TvContract.WatchedPrograms.COLUMN_WATCH_START_TIME_UTC_MILLIS,
1793                    TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS,
1794                    TvContract.WatchedPrograms.COLUMN_TITLE,
1795                    TvContract.WatchedPrograms.COLUMN_START_TIME_UTC_MILLIS,
1796                    TvContract.WatchedPrograms.COLUMN_END_TIME_UTC_MILLIS,
1797                    TvContract.WatchedPrograms.COLUMN_DESCRIPTION
1798            };
1799            Cursor cursor = null;
1800            try {
1801                cursor = mContentResolver.query(uri, projection, null, null, null);
1802                if (cursor != null && cursor.moveToNext()) {
1803                    long watchStartTime = cursor.getLong(0);
1804                    long watchEndTime = cursor.getLong(1);
1805                    String title = cursor.getString(2);
1806                    long startTime = cursor.getLong(3);
1807                    long endTime = cursor.getLong(4);
1808                    String description = cursor.getString(5);
1809
1810                    // Do nothing if the current log entry is already closed.
1811                    if (watchEndTime > 0) {
1812                        return;
1813                    }
1814
1815                    // The current program has just ended. Create a (complete) log entry off the
1816                    // current entry.
1817                    ContentValues values = new ContentValues();
1818                    values.put(TvContract.WatchedPrograms.COLUMN_WATCH_START_TIME_UTC_MILLIS,
1819                            watchStartTime);
1820                    values.put(TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS, time);
1821                    values.put(TvContract.WatchedPrograms.COLUMN_CHANNEL_ID, channelId);
1822                    values.put(TvContract.WatchedPrograms.COLUMN_TITLE, title);
1823                    values.put(TvContract.WatchedPrograms.COLUMN_START_TIME_UTC_MILLIS, startTime);
1824                    values.put(TvContract.WatchedPrograms.COLUMN_END_TIME_UTC_MILLIS, endTime);
1825                    values.put(TvContract.WatchedPrograms.COLUMN_DESCRIPTION, description);
1826                    mContentResolver.insert(TvContract.WatchedPrograms.CONTENT_URI, values);
1827                }
1828            } finally {
1829                if (cursor != null) {
1830                    cursor.close();
1831                }
1832            }
1833            // Re-open the current log entry with the next program information.
1834            onOpenEntry(uri, channelId, time);
1835        }
1836
1837        private void onCloseEntry(Uri uri, long watchEndTime) {
1838            ContentValues values = new ContentValues();
1839            values.put(TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS, watchEndTime);
1840            mContentResolver.update(uri, values, null, null);
1841        }
1842    }
1843
1844    final class HardwareListener implements TvInputHardwareManager.Listener {
1845        @Override
1846        public void onStateChanged(String inputId, int state) {
1847            synchronized (mLock) {
1848                setStateLocked(inputId, state, mCurrentUserId);
1849            }
1850        }
1851
1852        @Override
1853        public void onHardwareDeviceAdded(TvInputHardwareInfo info) {
1854            synchronized (mLock) {
1855                UserState userState = getUserStateLocked(mCurrentUserId);
1856                // Broadcast the event to all hardware inputs.
1857                for (ServiceState serviceState : userState.serviceStateMap.values()) {
1858                    if (!serviceState.mIsHardware || serviceState.mService == null) continue;
1859                    try {
1860                        serviceState.mService.notifyHardwareAdded(info);
1861                    } catch (RemoteException e) {
1862                        Slog.e(TAG, "error in notifyHardwareAdded", e);
1863                    }
1864                }
1865            }
1866        }
1867
1868        @Override
1869        public void onHardwareDeviceRemoved(TvInputHardwareInfo info) {
1870            synchronized (mLock) {
1871                UserState userState = getUserStateLocked(mCurrentUserId);
1872                // Broadcast the event to all hardware inputs.
1873                for (ServiceState serviceState : userState.serviceStateMap.values()) {
1874                    if (!serviceState.mIsHardware || serviceState.mService == null) continue;
1875                    try {
1876                        serviceState.mService.notifyHardwareRemoved(info);
1877                    } catch (RemoteException e) {
1878                        Slog.e(TAG, "error in notifyHardwareRemoved", e);
1879                    }
1880                }
1881            }
1882        }
1883
1884        @Override
1885        public void onHdmiCecDeviceAdded(HdmiCecDeviceInfo cecDeviceInfo) {
1886            synchronized (mLock) {
1887                UserState userState = getUserStateLocked(mCurrentUserId);
1888                // Broadcast the event to all hardware inputs.
1889                for (ServiceState serviceState : userState.serviceStateMap.values()) {
1890                    if (!serviceState.mIsHardware || serviceState.mService == null) continue;
1891                    try {
1892                        serviceState.mService.notifyHdmiCecDeviceAdded(cecDeviceInfo);
1893                    } catch (RemoteException e) {
1894                        Slog.e(TAG, "error in notifyHdmiCecDeviceAdded", e);
1895                    }
1896                }
1897            }
1898        }
1899
1900        @Override
1901        public void onHdmiCecDeviceRemoved(HdmiCecDeviceInfo cecDeviceInfo) {
1902            synchronized (mLock) {
1903                UserState userState = getUserStateLocked(mCurrentUserId);
1904                // Broadcast the event to all hardware inputs.
1905                for (ServiceState serviceState : userState.serviceStateMap.values()) {
1906                    if (!serviceState.mIsHardware || serviceState.mService == null) continue;
1907                    try {
1908                        serviceState.mService.notifyHdmiCecDeviceRemoved(cecDeviceInfo);
1909                    } catch (RemoteException e) {
1910                        Slog.e(TAG, "error in notifyHdmiCecDeviceRemoved", e);
1911                    }
1912                }
1913            }
1914        }
1915    }
1916}
1917