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