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