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