TvInputManagerService.java revision a759b111a1c9cb00284038f8a1554bf29709b952
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 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 void registerTvInputInfo(TvInputInfo info, int deviceId) {
1217            // TODO: Revisit to sort out deviceId ownership.
1218            if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1219                    != PackageManager.PERMISSION_GRANTED) {
1220                return;
1221            }
1222
1223            final long identity = Binder.clearCallingIdentity();
1224            try {
1225                mTvInputHardwareManager.registerTvInputInfo(info, deviceId);
1226            } finally {
1227                Binder.restoreCallingIdentity(identity);
1228            }
1229        }
1230
1231        @Override
1232        public ITvInputHardware acquireTvInputHardware(int deviceId,
1233                ITvInputHardwareCallback callback, TvInputInfo info, int userId)
1234                throws RemoteException {
1235            if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1236                    != PackageManager.PERMISSION_GRANTED) {
1237                return null;
1238            }
1239
1240            final long identity = Binder.clearCallingIdentity();
1241            final int callingUid = Binder.getCallingUid();
1242            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1243                    userId, "acquireTvInputHardware");
1244            try {
1245                return mTvInputHardwareManager.acquireHardware(
1246                        deviceId, callback, info, callingUid, resolvedUserId);
1247            } finally {
1248                Binder.restoreCallingIdentity(identity);
1249            }
1250        }
1251
1252        @Override
1253        public void releaseTvInputHardware(int deviceId, ITvInputHardware hardware, int userId)
1254                throws RemoteException {
1255            if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1256                    != PackageManager.PERMISSION_GRANTED) {
1257                return;
1258            }
1259
1260            final long identity = Binder.clearCallingIdentity();
1261            final int callingUid = Binder.getCallingUid();
1262            final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
1263                    userId, "releaseTvInputHardware");
1264            try {
1265                mTvInputHardwareManager.releaseHardware(
1266                        deviceId, hardware, callingUid, resolvedUserId);
1267            } finally {
1268                Binder.restoreCallingIdentity(identity);
1269            }
1270        }
1271
1272        @Override
1273        @SuppressWarnings("resource")
1274        protected void dump(FileDescriptor fd, final PrintWriter writer, String[] args) {
1275            final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
1276            if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1277                    != PackageManager.PERMISSION_GRANTED) {
1278                pw.println("Permission Denial: can't dump TvInputManager from pid="
1279                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
1280                return;
1281            }
1282
1283            synchronized (mLock) {
1284                pw.println("User Ids (Current user: " + mCurrentUserId + "):");
1285                pw.increaseIndent();
1286                for (int i = 0; i < mUserStates.size(); i++) {
1287                    int userId = mUserStates.keyAt(i);
1288                    pw.println(Integer.valueOf(userId));
1289                }
1290                pw.decreaseIndent();
1291
1292                for (int i = 0; i < mUserStates.size(); i++) {
1293                    int userId = mUserStates.keyAt(i);
1294                    UserState userState = getUserStateLocked(userId);
1295                    pw.println("UserState (" + userId + "):");
1296                    pw.increaseIndent();
1297
1298                    pw.println("inputMap: inputId -> TvInputState");
1299                    pw.increaseIndent();
1300                    for (Map.Entry<String, TvInputState> entry: userState.inputMap.entrySet()) {
1301                        pw.println(entry.getKey() + ": " + entry.getValue());
1302                    }
1303                    pw.decreaseIndent();
1304
1305                    pw.println("packageSet:");
1306                    pw.increaseIndent();
1307                    for (String packageName : userState.packageSet) {
1308                        pw.println(packageName);
1309                    }
1310                    pw.decreaseIndent();
1311
1312                    pw.println("clientStateMap: ITvInputClient -> ClientState");
1313                    pw.increaseIndent();
1314                    for (Map.Entry<IBinder, ClientState> entry :
1315                            userState.clientStateMap.entrySet()) {
1316                        ClientState client = entry.getValue();
1317                        pw.println(entry.getKey() + ": " + client);
1318
1319                        pw.increaseIndent();
1320
1321                        pw.println("mInputIds:");
1322                        pw.increaseIndent();
1323                        for (String inputId : client.mInputIds) {
1324                            pw.println(inputId);
1325                        }
1326                        pw.decreaseIndent();
1327
1328                        pw.println("mSessionTokens:");
1329                        pw.increaseIndent();
1330                        for (IBinder token : client.mSessionTokens) {
1331                            pw.println("" + token);
1332                        }
1333                        pw.decreaseIndent();
1334
1335                        pw.println("mClientTokens: " + client.mClientToken);
1336                        pw.println("mUserId: " + client.mUserId);
1337
1338                        pw.decreaseIndent();
1339                    }
1340                    pw.decreaseIndent();
1341
1342                    pw.println("serviceStateMap: ComponentName -> ServiceState");
1343                    pw.increaseIndent();
1344                    for (Map.Entry<ComponentName, ServiceState> entry :
1345                            userState.serviceStateMap.entrySet()) {
1346                        ServiceState service = entry.getValue();
1347                        pw.println(entry.getKey() + ": " + service);
1348
1349                        pw.increaseIndent();
1350
1351                        pw.println("mClientTokens:");
1352                        pw.increaseIndent();
1353                        for (IBinder token : service.mClientTokens) {
1354                            pw.println("" + token);
1355                        }
1356                        pw.decreaseIndent();
1357
1358                        pw.println("mSessionTokens:");
1359                        pw.increaseIndent();
1360                        for (IBinder token : service.mSessionTokens) {
1361                            pw.println("" + token);
1362                        }
1363                        pw.decreaseIndent();
1364
1365                        pw.println("mService: " + service.mService);
1366                        pw.println("mCallback: " + service.mCallback);
1367                        pw.println("mBound: " + service.mBound);
1368                        pw.println("mReconnecting: " + service.mReconnecting);
1369
1370                        pw.decreaseIndent();
1371                    }
1372                    pw.decreaseIndent();
1373
1374                    pw.println("sessionStateMap: ITvInputSession -> SessionState");
1375                    pw.increaseIndent();
1376                    for (Map.Entry<IBinder, SessionState> entry :
1377                            userState.sessionStateMap.entrySet()) {
1378                        SessionState session = entry.getValue();
1379                        pw.println(entry.getKey() + ": " + session);
1380
1381                        pw.increaseIndent();
1382                        pw.println("mInfo: " + session.mInfo);
1383                        pw.println("mClient: " + session.mClient);
1384                        pw.println("mSeq: " + session.mSeq);
1385                        pw.println("mCallingUid: " + session.mCallingUid);
1386                        pw.println("mUserId: " + session.mUserId);
1387                        pw.println("mSessionToken: " + session.mSessionToken);
1388                        pw.println("mSession: " + session.mSession);
1389                        pw.println("mLogUri: " + session.mLogUri);
1390                        pw.decreaseIndent();
1391                    }
1392                    pw.decreaseIndent();
1393
1394                    pw.println("callbackSet:");
1395                    pw.increaseIndent();
1396                    for (ITvInputManagerCallback callback : userState.callbackSet) {
1397                        pw.println(callback.toString());
1398                    }
1399                    pw.decreaseIndent();
1400
1401                    pw.decreaseIndent();
1402                }
1403            }
1404        }
1405    }
1406
1407    private static final class TvInputState {
1408        // A TvInputInfo object which represents the TV input.
1409        private TvInputInfo mInfo;
1410
1411        // The state of TV input. Connected by default.
1412        private int mState = INPUT_STATE_CONNECTED;
1413
1414        @Override
1415        public String toString() {
1416            return "mInfo: " + mInfo + "; mState: " + mState;
1417        }
1418    }
1419
1420    private static final class UserState {
1421        // A mapping from the TV input id to its TvInputState.
1422        private Map<String, TvInputState> inputMap = new HashMap<String, TvInputState>();
1423
1424        // A set of all TV input packages.
1425        private final Set<String> packageSet = new HashSet<String>();
1426
1427        // A mapping from the token of a client to its state.
1428        private final Map<IBinder, ClientState> clientStateMap =
1429                new HashMap<IBinder, ClientState>();
1430
1431        // A mapping from the name of a TV input service to its state.
1432        private final Map<ComponentName, ServiceState> serviceStateMap =
1433                new HashMap<ComponentName, ServiceState>();
1434
1435        // A mapping from the token of a TV input session to its state.
1436        private final Map<IBinder, SessionState> sessionStateMap =
1437                new HashMap<IBinder, SessionState>();
1438
1439        // A set of callbacks.
1440        private final Set<ITvInputManagerCallback> callbackSet =
1441                new HashSet<ITvInputManagerCallback>();
1442    }
1443
1444    private final class ClientState implements IBinder.DeathRecipient {
1445        private final List<String> mInputIds = new ArrayList<String>();
1446        private final List<IBinder> mSessionTokens = new ArrayList<IBinder>();
1447
1448        private IBinder mClientToken;
1449        private final int mUserId;
1450
1451        ClientState(IBinder clientToken, int userId) {
1452            mClientToken = clientToken;
1453            mUserId = userId;
1454        }
1455
1456        public boolean isEmpty() {
1457            return mInputIds.isEmpty() && mSessionTokens.isEmpty();
1458        }
1459
1460        @Override
1461        public void binderDied() {
1462            synchronized (mLock) {
1463                UserState userState = getUserStateLocked(mUserId);
1464                // DO NOT remove the client state of clientStateMap in this method. It will be
1465                // removed in releaseSessionLocked() or unregisterClientInternalLocked().
1466                ClientState clientState = userState.clientStateMap.get(mClientToken);
1467                if (clientState != null) {
1468                    while (clientState.mSessionTokens.size() > 0) {
1469                        releaseSessionLocked(
1470                                clientState.mSessionTokens.get(0), Process.SYSTEM_UID, mUserId);
1471                    }
1472                    while (clientState.mInputIds.size() > 0) {
1473                        unregisterClientInternalLocked(
1474                                mClientToken, clientState.mInputIds.get(0), mUserId);
1475                    }
1476                }
1477                mClientToken = null;
1478            }
1479        }
1480    }
1481
1482    private final class ServiceState {
1483        private final List<IBinder> mClientTokens = new ArrayList<IBinder>();
1484        private final List<IBinder> mSessionTokens = new ArrayList<IBinder>();
1485        private final ServiceConnection mConnection;
1486        private final ComponentName mName;
1487        private final boolean mIsHardware;
1488        private final List<TvInputInfo> mInputList = new ArrayList<TvInputInfo>();
1489
1490        private ITvInputService mService;
1491        private ServiceCallback mCallback;
1492        private boolean mBound;
1493        private boolean mReconnecting;
1494
1495        private ServiceState(ComponentName name, int userId) {
1496            mName = name;
1497            mConnection = new InputServiceConnection(name, userId);
1498            mIsHardware = hasHardwarePermission(mContext.getPackageManager(), mName);
1499        }
1500    }
1501
1502    private final class SessionState implements IBinder.DeathRecipient {
1503        private final TvInputInfo mInfo;
1504        private final ITvInputClient mClient;
1505        private final int mSeq;
1506        private final int mCallingUid;
1507        private final int mUserId;
1508        private final IBinder mSessionToken;
1509        private ITvInputSession mSession;
1510        private Uri mLogUri;
1511
1512        private SessionState(IBinder sessionToken, TvInputInfo info, ITvInputClient client, int seq,
1513                int callingUid, int userId) {
1514            mSessionToken = sessionToken;
1515            mInfo = info;
1516            mClient = client;
1517            mSeq = seq;
1518            mCallingUid = callingUid;
1519            mUserId = userId;
1520        }
1521
1522        @Override
1523        public void binderDied() {
1524            synchronized (mLock) {
1525                mSession = null;
1526                if (mClient != null) {
1527                    try {
1528                        mClient.onSessionReleased(mSeq);
1529                    } catch(RemoteException e) {
1530                        Slog.e(TAG, "error in onSessionReleased", e);
1531                    }
1532                }
1533                removeSessionStateLocked(mSessionToken, mUserId);
1534            }
1535        }
1536    }
1537
1538    private final class InputServiceConnection implements ServiceConnection {
1539        private final ComponentName mName;
1540        private final int mUserId;
1541
1542        private InputServiceConnection(ComponentName name, int userId) {
1543            mName = name;
1544            mUserId = userId;
1545        }
1546
1547        @Override
1548        public void onServiceConnected(ComponentName name, IBinder service) {
1549            if (DEBUG) {
1550                Slog.d(TAG, "onServiceConnected(name=" + name + ")");
1551            }
1552            synchronized (mLock) {
1553                List<TvInputHardwareInfo> hardwareInfoList =
1554                        mTvInputHardwareManager.getHardwareList();
1555                UserState userState = getUserStateLocked(mUserId);
1556                ServiceState serviceState = userState.serviceStateMap.get(mName);
1557                serviceState.mService = ITvInputService.Stub.asInterface(service);
1558
1559                // Register a callback, if we need to.
1560                if (serviceState.mIsHardware && serviceState.mCallback == null) {
1561                    serviceState.mCallback = new ServiceCallback(mName, mUserId);
1562                    try {
1563                        serviceState.mService.registerCallback(serviceState.mCallback);
1564                    } catch (RemoteException e) {
1565                        Slog.e(TAG, "error in registerCallback", e);
1566                    }
1567                }
1568
1569                // And create sessions, if any.
1570                for (IBinder sessionToken : serviceState.mSessionTokens) {
1571                    createSessionInternalLocked(serviceState.mService, sessionToken, mUserId);
1572                }
1573
1574                for (TvInputState inputState : userState.inputMap.values()) {
1575                    if (inputState.mInfo.getComponent().equals(name)
1576                            && inputState.mState != INPUT_STATE_DISCONNECTED) {
1577                        notifyInputStateChangedLocked(userState, inputState.mInfo.getId(),
1578                                inputState.mState, null);
1579                    }
1580                }
1581
1582                if (serviceState.mIsHardware) {
1583                    for (TvInputHardwareInfo hardwareInfo : hardwareInfoList) {
1584                        try {
1585                            serviceState.mService.notifyHardwareAdded(hardwareInfo);
1586                        } catch (RemoteException e) {
1587                            Slog.e(TAG, "error in notifyHardwareAdded", e);
1588                        }
1589                    }
1590
1591                    // TODO: Grab CEC devices and notify them to the service.
1592                }
1593            }
1594        }
1595
1596        @Override
1597        public void onServiceDisconnected(ComponentName name) {
1598            if (DEBUG) {
1599                Slog.d(TAG, "onServiceDisconnected(name=" + name + ")");
1600            }
1601            if (!mName.equals(name)) {
1602                throw new IllegalArgumentException("Mismatched ComponentName: "
1603                        + mName + " (expected), " + name + " (actual).");
1604            }
1605            synchronized (mLock) {
1606                UserState userState = getUserStateLocked(mUserId);
1607                ServiceState serviceState = userState.serviceStateMap.get(mName);
1608                if (serviceState != null) {
1609                    serviceState.mReconnecting = true;
1610                    serviceState.mBound = false;
1611                    serviceState.mService = null;
1612                    serviceState.mCallback = null;
1613
1614                    // Send null tokens for not finishing create session events.
1615                    for (IBinder sessionToken : serviceState.mSessionTokens) {
1616                        SessionState sessionState = userState.sessionStateMap.get(sessionToken);
1617                        if (sessionState.mSession == null) {
1618                            removeSessionStateLocked(sessionToken, sessionState.mUserId);
1619                            sendSessionTokenToClientLocked(sessionState.mClient,
1620                                    sessionState.mInfo.getId(), null, null, sessionState.mSeq);
1621                        }
1622                    }
1623
1624                    for (TvInputState inputState : userState.inputMap.values()) {
1625                        if (inputState.mInfo.getComponent().equals(name)) {
1626                            notifyInputStateChangedLocked(userState, inputState.mInfo.getId(),
1627                                    INPUT_STATE_DISCONNECTED, null);
1628                        }
1629                    }
1630                    updateServiceConnectionLocked(mName, mUserId);
1631                }
1632            }
1633        }
1634    }
1635
1636    private final class ServiceCallback extends ITvInputServiceCallback.Stub {
1637        private final ComponentName mName;
1638        private final int mUserId;
1639
1640        ServiceCallback(ComponentName name, int userId) {
1641            mName = name;
1642            mUserId = userId;
1643        }
1644
1645        @Override
1646        public void addTvInput(TvInputInfo inputInfo) {
1647            synchronized (mLock) {
1648                if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1649                        != PackageManager.PERMISSION_GRANTED) {
1650                    Slog.w(TAG, "The caller does not have permission to add a TV input ("
1651                            + inputInfo + ").");
1652                    return;
1653                }
1654
1655                ServiceState serviceState = getServiceStateLocked(mName, mUserId);
1656                serviceState.mInputList.add(inputInfo);
1657                buildTvInputListLocked(mUserId);
1658            }
1659        }
1660
1661        @Override
1662        public void removeTvInput(String inputId) {
1663            synchronized (mLock) {
1664                if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1665                        != PackageManager.PERMISSION_GRANTED) {
1666                    Slog.w(TAG, "The caller does not have permission to remove a TV input ("
1667                            + inputId + ").");
1668                    return;
1669                }
1670
1671                ServiceState serviceState = getServiceStateLocked(mName, mUserId);
1672                boolean removed = false;
1673                for (Iterator<TvInputInfo> it = serviceState.mInputList.iterator();
1674                        it.hasNext(); ) {
1675                    if (it.next().getId().equals(inputId)) {
1676                        it.remove();
1677                        removed = true;
1678                        break;
1679                    }
1680                }
1681                if (removed) {
1682                    buildTvInputListLocked(mUserId);
1683                } else {
1684                    Slog.e(TAG, "TvInputInfo with inputId=" + inputId + " not found.");
1685                }
1686            }
1687        }
1688    }
1689
1690    private final class LogHandler extends Handler {
1691        private static final int MSG_OPEN_ENTRY = 1;
1692        private static final int MSG_UPDATE_ENTRY = 2;
1693        private static final int MSG_CLOSE_ENTRY = 3;
1694
1695        public LogHandler(Looper looper) {
1696            super(looper);
1697        }
1698
1699        @Override
1700        public void handleMessage(Message msg) {
1701            switch (msg.what) {
1702                case MSG_OPEN_ENTRY: {
1703                    SomeArgs args = (SomeArgs) msg.obj;
1704                    Uri uri = (Uri) args.arg1;
1705                    long channelId = (long) args.arg2;
1706                    long time = (long) args.arg3;
1707                    onOpenEntry(uri, channelId, time);
1708                    args.recycle();
1709                    return;
1710                }
1711                case MSG_UPDATE_ENTRY: {
1712                    SomeArgs args = (SomeArgs) msg.obj;
1713                    Uri uri = (Uri) args.arg1;
1714                    long channelId = (long) args.arg2;
1715                    long time = (long) args.arg3;
1716                    onUpdateEntry(uri, channelId, time);
1717                    args.recycle();
1718                    return;
1719                }
1720                case MSG_CLOSE_ENTRY: {
1721                    SomeArgs args = (SomeArgs) msg.obj;
1722                    Uri uri = (Uri) args.arg1;
1723                    long time = (long) args.arg2;
1724                    onCloseEntry(uri, time);
1725                    args.recycle();
1726                    return;
1727                }
1728                default: {
1729                    Slog.w(TAG, "Unhandled message code: " + msg.what);
1730                    return;
1731                }
1732            }
1733        }
1734
1735        private void onOpenEntry(Uri uri, long channelId, long watchStarttime) {
1736            String[] projection = {
1737                    TvContract.Programs.COLUMN_TITLE,
1738                    TvContract.Programs.COLUMN_START_TIME_UTC_MILLIS,
1739                    TvContract.Programs.COLUMN_END_TIME_UTC_MILLIS,
1740                    TvContract.Programs.COLUMN_SHORT_DESCRIPTION
1741            };
1742            String selection = TvContract.Programs.COLUMN_CHANNEL_ID + "=? AND "
1743                    + TvContract.Programs.COLUMN_START_TIME_UTC_MILLIS + "<=? AND "
1744                    + TvContract.Programs.COLUMN_END_TIME_UTC_MILLIS + ">?";
1745            String[] selectionArgs = {
1746                    String.valueOf(channelId),
1747                    String.valueOf(watchStarttime),
1748                    String.valueOf(watchStarttime)
1749            };
1750            String sortOrder = TvContract.Programs.COLUMN_START_TIME_UTC_MILLIS + " ASC";
1751            Cursor cursor = null;
1752            try {
1753                cursor = mContentResolver.query(TvContract.Programs.CONTENT_URI, projection,
1754                        selection, selectionArgs, sortOrder);
1755                if (cursor != null && cursor.moveToNext()) {
1756                    ContentValues values = new ContentValues();
1757                    values.put(TvContract.WatchedPrograms.COLUMN_TITLE, cursor.getString(0));
1758                    values.put(TvContract.WatchedPrograms.COLUMN_START_TIME_UTC_MILLIS,
1759                            cursor.getLong(1));
1760                    long endTime = cursor.getLong(2);
1761                    values.put(TvContract.WatchedPrograms.COLUMN_END_TIME_UTC_MILLIS, endTime);
1762                    values.put(TvContract.WatchedPrograms.COLUMN_DESCRIPTION, cursor.getString(3));
1763                    mContentResolver.update(uri, values, null, null);
1764
1765                    // Schedule an update when the current program ends.
1766                    SomeArgs args = SomeArgs.obtain();
1767                    args.arg1 = uri;
1768                    args.arg2 = channelId;
1769                    args.arg3 = endTime;
1770                    Message msg = obtainMessage(LogHandler.MSG_UPDATE_ENTRY, args);
1771                    sendMessageDelayed(msg, endTime - System.currentTimeMillis());
1772                }
1773            } finally {
1774                if (cursor != null) {
1775                    cursor.close();
1776                }
1777            }
1778        }
1779
1780        private void onUpdateEntry(Uri uri, long channelId, long time) {
1781            String[] projection = {
1782                    TvContract.WatchedPrograms.COLUMN_WATCH_START_TIME_UTC_MILLIS,
1783                    TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS,
1784                    TvContract.WatchedPrograms.COLUMN_TITLE,
1785                    TvContract.WatchedPrograms.COLUMN_START_TIME_UTC_MILLIS,
1786                    TvContract.WatchedPrograms.COLUMN_END_TIME_UTC_MILLIS,
1787                    TvContract.WatchedPrograms.COLUMN_DESCRIPTION
1788            };
1789            Cursor cursor = null;
1790            try {
1791                cursor = mContentResolver.query(uri, projection, null, null, null);
1792                if (cursor != null && cursor.moveToNext()) {
1793                    long watchStartTime = cursor.getLong(0);
1794                    long watchEndTime = cursor.getLong(1);
1795                    String title = cursor.getString(2);
1796                    long startTime = cursor.getLong(3);
1797                    long endTime = cursor.getLong(4);
1798                    String description = cursor.getString(5);
1799
1800                    // Do nothing if the current log entry is already closed.
1801                    if (watchEndTime > 0) {
1802                        return;
1803                    }
1804
1805                    // The current program has just ended. Create a (complete) log entry off the
1806                    // current entry.
1807                    ContentValues values = new ContentValues();
1808                    values.put(TvContract.WatchedPrograms.COLUMN_WATCH_START_TIME_UTC_MILLIS,
1809                            watchStartTime);
1810                    values.put(TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS, time);
1811                    values.put(TvContract.WatchedPrograms.COLUMN_CHANNEL_ID, channelId);
1812                    values.put(TvContract.WatchedPrograms.COLUMN_TITLE, title);
1813                    values.put(TvContract.WatchedPrograms.COLUMN_START_TIME_UTC_MILLIS, startTime);
1814                    values.put(TvContract.WatchedPrograms.COLUMN_END_TIME_UTC_MILLIS, endTime);
1815                    values.put(TvContract.WatchedPrograms.COLUMN_DESCRIPTION, description);
1816                    mContentResolver.insert(TvContract.WatchedPrograms.CONTENT_URI, values);
1817                }
1818            } finally {
1819                if (cursor != null) {
1820                    cursor.close();
1821                }
1822            }
1823            // Re-open the current log entry with the next program information.
1824            onOpenEntry(uri, channelId, time);
1825        }
1826
1827        private void onCloseEntry(Uri uri, long watchEndTime) {
1828            ContentValues values = new ContentValues();
1829            values.put(TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS, watchEndTime);
1830            mContentResolver.update(uri, values, null, null);
1831        }
1832    }
1833
1834    final class HardwareListener implements TvInputHardwareManager.Listener {
1835        @Override
1836        public void onStateChanged(String inputId, int state) {
1837            synchronized (mLock) {
1838                setStateLocked(inputId, state, mCurrentUserId);
1839            }
1840        }
1841
1842        @Override
1843        public void onHardwareDeviceAdded(TvInputHardwareInfo info) {
1844            synchronized (mLock) {
1845                UserState userState = getUserStateLocked(mCurrentUserId);
1846                // Broadcast the event to all hardware inputs.
1847                for (ServiceState serviceState : userState.serviceStateMap.values()) {
1848                    if (!serviceState.mIsHardware || serviceState.mService == null) continue;
1849                    try {
1850                        serviceState.mService.notifyHardwareAdded(info);
1851                    } catch (RemoteException e) {
1852                        Slog.e(TAG, "error in notifyHardwareAdded", e);
1853                    }
1854                }
1855            }
1856        }
1857
1858        @Override
1859        public void onHardwareDeviceRemoved(int deviceId) {
1860            synchronized (mLock) {
1861                UserState userState = getUserStateLocked(mCurrentUserId);
1862                // Broadcast the event to all hardware inputs.
1863                for (ServiceState serviceState : userState.serviceStateMap.values()) {
1864                    if (!serviceState.mIsHardware || serviceState.mService == null) continue;
1865                    try {
1866                        serviceState.mService.notifyHardwareRemoved(deviceId);
1867                    } catch (RemoteException e) {
1868                        Slog.e(TAG, "error in notifyHardwareRemoved", e);
1869                    }
1870                }
1871            }
1872        }
1873
1874        @Override
1875        public void onHdmiCecDeviceAdded(HdmiCecDeviceInfo cecDevice) {
1876            synchronized (mLock) {
1877                // TODO
1878            }
1879        }
1880
1881        @Override
1882        public void onHdmiCecDeviceRemoved(HdmiCecDeviceInfo cecDevice) {
1883            synchronized (mLock) {
1884                // TODO
1885            }
1886        }
1887    }
1888}
1889