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