TvInputManagerService.java revision 61f4fbd2e8436a1ecd478c2a1f516d064a24d43b
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        @SuppressWarnings("resource")
1526        protected void dump(FileDescriptor fd, final PrintWriter writer, String[] args) {
1527            final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
1528            if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1529                    != PackageManager.PERMISSION_GRANTED) {
1530                pw.println("Permission Denial: can't dump TvInputManager from pid="
1531                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
1532                return;
1533            }
1534
1535            synchronized (mLock) {
1536                pw.println("User Ids (Current user: " + mCurrentUserId + "):");
1537                pw.increaseIndent();
1538                for (int i = 0; i < mUserStates.size(); i++) {
1539                    int userId = mUserStates.keyAt(i);
1540                    pw.println(Integer.valueOf(userId));
1541                }
1542                pw.decreaseIndent();
1543
1544                for (int i = 0; i < mUserStates.size(); i++) {
1545                    int userId = mUserStates.keyAt(i);
1546                    UserState userState = getUserStateLocked(userId);
1547                    pw.println("UserState (" + userId + "):");
1548                    pw.increaseIndent();
1549
1550                    pw.println("inputMap: inputId -> TvInputState");
1551                    pw.increaseIndent();
1552                    for (Map.Entry<String, TvInputState> entry: userState.inputMap.entrySet()) {
1553                        pw.println(entry.getKey() + ": " + entry.getValue());
1554                    }
1555                    pw.decreaseIndent();
1556
1557                    pw.println("packageSet:");
1558                    pw.increaseIndent();
1559                    for (String packageName : userState.packageSet) {
1560                        pw.println(packageName);
1561                    }
1562                    pw.decreaseIndent();
1563
1564                    pw.println("clientStateMap: ITvInputClient -> ClientState");
1565                    pw.increaseIndent();
1566                    for (Map.Entry<IBinder, ClientState> entry :
1567                            userState.clientStateMap.entrySet()) {
1568                        ClientState client = entry.getValue();
1569                        pw.println(entry.getKey() + ": " + client);
1570
1571                        pw.increaseIndent();
1572
1573                        pw.println("mSessionTokens:");
1574                        pw.increaseIndent();
1575                        for (IBinder token : client.mSessionTokens) {
1576                            pw.println("" + token);
1577                        }
1578                        pw.decreaseIndent();
1579
1580                        pw.println("mClientTokens: " + client.mClientToken);
1581                        pw.println("mUserId: " + client.mUserId);
1582
1583                        pw.decreaseIndent();
1584                    }
1585                    pw.decreaseIndent();
1586
1587                    pw.println("serviceStateMap: ComponentName -> ServiceState");
1588                    pw.increaseIndent();
1589                    for (Map.Entry<ComponentName, ServiceState> entry :
1590                            userState.serviceStateMap.entrySet()) {
1591                        ServiceState service = entry.getValue();
1592                        pw.println(entry.getKey() + ": " + service);
1593
1594                        pw.increaseIndent();
1595
1596                        pw.println("mClientTokens:");
1597                        pw.increaseIndent();
1598                        for (IBinder token : service.mClientTokens) {
1599                            pw.println("" + token);
1600                        }
1601                        pw.decreaseIndent();
1602
1603                        pw.println("mSessionTokens:");
1604                        pw.increaseIndent();
1605                        for (IBinder token : service.mSessionTokens) {
1606                            pw.println("" + token);
1607                        }
1608                        pw.decreaseIndent();
1609
1610                        pw.println("mService: " + service.mService);
1611                        pw.println("mCallback: " + service.mCallback);
1612                        pw.println("mBound: " + service.mBound);
1613                        pw.println("mReconnecting: " + service.mReconnecting);
1614
1615                        pw.decreaseIndent();
1616                    }
1617                    pw.decreaseIndent();
1618
1619                    pw.println("sessionStateMap: ITvInputSession -> SessionState");
1620                    pw.increaseIndent();
1621                    for (Map.Entry<IBinder, SessionState> entry :
1622                            userState.sessionStateMap.entrySet()) {
1623                        SessionState session = entry.getValue();
1624                        pw.println(entry.getKey() + ": " + session);
1625
1626                        pw.increaseIndent();
1627                        pw.println("mInfo: " + session.mInfo);
1628                        pw.println("mClient: " + session.mClient);
1629                        pw.println("mSeq: " + session.mSeq);
1630                        pw.println("mCallingUid: " + session.mCallingUid);
1631                        pw.println("mUserId: " + session.mUserId);
1632                        pw.println("mSessionToken: " + session.mSessionToken);
1633                        pw.println("mSession: " + session.mSession);
1634                        pw.println("mLogUri: " + session.mLogUri);
1635                        pw.println("mHardwareSessionToken: " + session.mHardwareSessionToken);
1636                        pw.decreaseIndent();
1637                    }
1638                    pw.decreaseIndent();
1639
1640                    pw.println("callbackSet:");
1641                    pw.increaseIndent();
1642                    for (ITvInputManagerCallback callback : userState.callbackSet) {
1643                        pw.println(callback.toString());
1644                    }
1645                    pw.decreaseIndent();
1646
1647                    pw.decreaseIndent();
1648                }
1649            }
1650        }
1651
1652        private String encodeTuneParams(Bundle tuneParams) {
1653            StringBuilder builder = new StringBuilder();
1654            Set<String> keySet = tuneParams.keySet();
1655            Iterator<String> it = keySet.iterator();
1656            while (it.hasNext()) {
1657                String key = it.next();
1658                Object value = tuneParams.get(key);
1659                if (value == null) {
1660                    continue;
1661                }
1662                builder.append(replaceEscapeCharacters(key));
1663                builder.append("=");
1664                builder.append(replaceEscapeCharacters(value.toString()));
1665                if (it.hasNext()) {
1666                    builder.append(", ");
1667                }
1668            }
1669            return builder.toString();
1670        }
1671
1672        private String replaceEscapeCharacters(String src) {
1673            final char ESCAPE_CHARACTER = '%';
1674            final String ENCODING_TARGET_CHARACTERS = "%=,";
1675            StringBuilder builder = new StringBuilder();
1676            for (char ch : src.toCharArray()) {
1677                if (ENCODING_TARGET_CHARACTERS.indexOf(ch) >= 0) {
1678                    builder.append(ESCAPE_CHARACTER);
1679                }
1680                builder.append(ch);
1681            }
1682            return builder.toString();
1683        }
1684    }
1685
1686    private static final class TvInputState {
1687        // A TvInputInfo object which represents the TV input.
1688        private TvInputInfo mInfo;
1689
1690        // The state of TV input. Connected by default.
1691        private int mState = INPUT_STATE_CONNECTED;
1692
1693        @Override
1694        public String toString() {
1695            return "mInfo: " + mInfo + "; mState: " + mState;
1696        }
1697    }
1698
1699    private static final class UserState {
1700        // A mapping from the TV input id to its TvInputState.
1701        private Map<String, TvInputState> inputMap = new HashMap<String, TvInputState>();
1702
1703        // A set of all TV input packages.
1704        private final Set<String> packageSet = new HashSet<String>();
1705
1706        // A set of all TV content rating system xml uris.
1707        private final Set<Uri> ratingSystemXmlUriSet = new HashSet<Uri>();
1708
1709        // A mapping from the token of a client to its state.
1710        private final Map<IBinder, ClientState> clientStateMap =
1711                new HashMap<IBinder, ClientState>();
1712
1713        // A mapping from the name of a TV input service to its state.
1714        private final Map<ComponentName, ServiceState> serviceStateMap =
1715                new HashMap<ComponentName, ServiceState>();
1716
1717        // A mapping from the token of a TV input session to its state.
1718        private final Map<IBinder, SessionState> sessionStateMap =
1719                new HashMap<IBinder, SessionState>();
1720
1721        // A set of callbacks.
1722        private final Set<ITvInputManagerCallback> callbackSet =
1723                new HashSet<ITvInputManagerCallback>();
1724
1725        // The token of a "main" TV input session.
1726        private IBinder mainSessionToken = null;
1727
1728        // Persistent data store for all internal settings maintained by the TV input manager
1729        // service.
1730        private final PersistentDataStore persistentDataStore;
1731
1732        private UserState(Context context, int userId) {
1733            persistentDataStore = new PersistentDataStore(context, userId);
1734        }
1735    }
1736
1737    private final class ClientState implements IBinder.DeathRecipient {
1738        private final List<IBinder> mSessionTokens = new ArrayList<IBinder>();
1739
1740        private IBinder mClientToken;
1741        private final int mUserId;
1742
1743        ClientState(IBinder clientToken, int userId) {
1744            mClientToken = clientToken;
1745            mUserId = userId;
1746        }
1747
1748        public boolean isEmpty() {
1749            return mSessionTokens.isEmpty();
1750        }
1751
1752        @Override
1753        public void binderDied() {
1754            synchronized (mLock) {
1755                UserState userState = getUserStateLocked(mUserId);
1756                // DO NOT remove the client state of clientStateMap in this method. It will be
1757                // removed in releaseSessionLocked().
1758                ClientState clientState = userState.clientStateMap.get(mClientToken);
1759                if (clientState != null) {
1760                    while (clientState.mSessionTokens.size() > 0) {
1761                        releaseSessionLocked(
1762                                clientState.mSessionTokens.get(0), Process.SYSTEM_UID, mUserId);
1763                    }
1764                }
1765                mClientToken = null;
1766            }
1767        }
1768    }
1769
1770    private final class ServiceState {
1771        private final List<IBinder> mClientTokens = new ArrayList<IBinder>();
1772        private final List<IBinder> mSessionTokens = new ArrayList<IBinder>();
1773        private final ServiceConnection mConnection;
1774        private final ComponentName mComponent;
1775        private final boolean mIsHardware;
1776        private final List<TvInputInfo> mInputList = new ArrayList<TvInputInfo>();
1777
1778        private ITvInputService mService;
1779        private ServiceCallback mCallback;
1780        private boolean mBound;
1781        private boolean mReconnecting;
1782
1783        private ServiceState(ComponentName component, int userId) {
1784            mComponent = component;
1785            mConnection = new InputServiceConnection(component, userId);
1786            mIsHardware = hasHardwarePermission(mContext.getPackageManager(), mComponent);
1787        }
1788    }
1789
1790    private final class SessionState implements IBinder.DeathRecipient {
1791        private final TvInputInfo mInfo;
1792        private final ITvInputClient mClient;
1793        private final int mSeq;
1794        private final int mCallingUid;
1795        private final int mUserId;
1796        private final IBinder mSessionToken;
1797        private ITvInputSession mSession;
1798        private Uri mLogUri;
1799        // Not null if this session represents an external device connected to a hardware TV input.
1800        private IBinder mHardwareSessionToken;
1801
1802        private SessionState(IBinder sessionToken, TvInputInfo info, ITvInputClient client,
1803                int seq, int callingUid, int userId) {
1804            mSessionToken = sessionToken;
1805            mInfo = info;
1806            mClient = client;
1807            mSeq = seq;
1808            mCallingUid = callingUid;
1809            mUserId = userId;
1810        }
1811
1812        @Override
1813        public void binderDied() {
1814            synchronized (mLock) {
1815                mSession = null;
1816                if (mClient != null) {
1817                    try {
1818                        mClient.onSessionReleased(mSeq);
1819                    } catch(RemoteException e) {
1820                        Slog.e(TAG, "error in onSessionReleased", e);
1821                    }
1822                }
1823                // If there are any other sessions based on this session, they should be released.
1824                UserState userState = getUserStateLocked(mUserId);
1825                for (SessionState sessionState : userState.sessionStateMap.values()) {
1826                    if (mSession != null && mSession == sessionState.mHardwareSessionToken) {
1827                        try {
1828                            sessionState.mSession.release();
1829                        } catch (RemoteException e) {
1830                            Slog.e(TAG, "error in release", e);
1831                        }
1832                        try {
1833                            sessionState.mClient.onSessionReleased(sessionState.mSeq);
1834                        } catch (RemoteException e) {
1835                            Slog.e(TAG, "error in onSessionReleased", e);
1836                        }
1837                    }
1838                }
1839                removeSessionStateLocked(mSessionToken, mUserId);
1840            }
1841        }
1842    }
1843
1844    private final class InputServiceConnection implements ServiceConnection {
1845        private final ComponentName mComponent;
1846        private final int mUserId;
1847
1848        private InputServiceConnection(ComponentName component, int userId) {
1849            mComponent = component;
1850            mUserId = userId;
1851        }
1852
1853        @Override
1854        public void onServiceConnected(ComponentName component, IBinder service) {
1855            if (DEBUG) {
1856                Slog.d(TAG, "onServiceConnected(component=" + component + ")");
1857            }
1858            synchronized (mLock) {
1859                UserState userState = getUserStateLocked(mUserId);
1860                ServiceState serviceState = userState.serviceStateMap.get(mComponent);
1861                serviceState.mService = ITvInputService.Stub.asInterface(service);
1862
1863                // Register a callback, if we need to.
1864                if (serviceState.mIsHardware && serviceState.mCallback == null) {
1865                    serviceState.mCallback = new ServiceCallback(mComponent, mUserId);
1866                    try {
1867                        serviceState.mService.registerCallback(serviceState.mCallback);
1868                    } catch (RemoteException e) {
1869                        Slog.e(TAG, "error in registerCallback", e);
1870                    }
1871                }
1872
1873                // And create sessions, if any.
1874                for (IBinder sessionToken : serviceState.mSessionTokens) {
1875                    createSessionInternalLocked(serviceState.mService, sessionToken, mUserId);
1876                }
1877
1878                for (TvInputState inputState : userState.inputMap.values()) {
1879                    if (inputState.mInfo.getComponent().equals(component)
1880                            && inputState.mState != INPUT_STATE_DISCONNECTED) {
1881                        notifyInputStateChangedLocked(userState, inputState.mInfo.getId(),
1882                                inputState.mState, null);
1883                    }
1884                }
1885
1886                if (serviceState.mIsHardware) {
1887                    List<TvInputHardwareInfo> hardwareInfoList =
1888                            mTvInputHardwareManager.getHardwareList();
1889                    for (TvInputHardwareInfo hardwareInfo : hardwareInfoList) {
1890                        try {
1891                            serviceState.mService.notifyHardwareAdded(hardwareInfo);
1892                        } catch (RemoteException e) {
1893                            Slog.e(TAG, "error in notifyHardwareAdded", e);
1894                        }
1895                    }
1896
1897                    List<HdmiDeviceInfo> cecDeviceInfoList =
1898                            mTvInputHardwareManager.getHdmiCecInputDeviceList();
1899                    for (HdmiDeviceInfo cecDeviceInfo : cecDeviceInfoList) {
1900                        try {
1901                            serviceState.mService.notifyHdmiCecDeviceAdded(cecDeviceInfo);
1902                        } catch (RemoteException e) {
1903                            Slog.e(TAG, "error in notifyHdmiCecDeviceAdded", e);
1904                        }
1905                    }
1906                }
1907            }
1908        }
1909
1910        @Override
1911        public void onServiceDisconnected(ComponentName component) {
1912            if (DEBUG) {
1913                Slog.d(TAG, "onServiceDisconnected(component=" + component + ")");
1914            }
1915            if (!mComponent.equals(component)) {
1916                throw new IllegalArgumentException("Mismatched ComponentName: "
1917                        + mComponent + " (expected), " + component + " (actual).");
1918            }
1919            synchronized (mLock) {
1920                UserState userState = getUserStateLocked(mUserId);
1921                ServiceState serviceState = userState.serviceStateMap.get(mComponent);
1922                if (serviceState != null) {
1923                    serviceState.mReconnecting = true;
1924                    serviceState.mBound = false;
1925                    serviceState.mService = null;
1926                    serviceState.mCallback = null;
1927
1928                    // Send null tokens for not finishing create session events.
1929                    for (IBinder sessionToken : serviceState.mSessionTokens) {
1930                        SessionState sessionState = userState.sessionStateMap.get(sessionToken);
1931                        if (sessionState.mSession == null) {
1932                            removeSessionStateLocked(sessionToken, sessionState.mUserId);
1933                            sendSessionTokenToClientLocked(sessionState.mClient,
1934                                    sessionState.mInfo.getId(), null, null, sessionState.mSeq);
1935                        }
1936                    }
1937
1938                    for (TvInputState inputState : userState.inputMap.values()) {
1939                        if (inputState.mInfo.getComponent().equals(component)) {
1940                            notifyInputStateChangedLocked(userState, inputState.mInfo.getId(),
1941                                    INPUT_STATE_DISCONNECTED, null);
1942                        }
1943                    }
1944                    updateServiceConnectionLocked(mComponent, mUserId);
1945                }
1946            }
1947        }
1948    }
1949
1950    private final class ServiceCallback extends ITvInputServiceCallback.Stub {
1951        private final ComponentName mComponent;
1952        private final int mUserId;
1953
1954        ServiceCallback(ComponentName component, int userId) {
1955            mComponent = component;
1956            mUserId = userId;
1957        }
1958
1959        private void ensureHardwarePermission() {
1960            if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE)
1961                    != PackageManager.PERMISSION_GRANTED) {
1962                throw new SecurityException("The caller does not have hardware permission");
1963            }
1964        }
1965
1966        private void ensureValidInput(TvInputInfo inputInfo) {
1967            if (inputInfo.getId() == null || !mComponent.equals(inputInfo.getComponent())) {
1968                throw new IllegalArgumentException("Invalid TvInputInfo");
1969            }
1970        }
1971
1972        private void addTvInputLocked(TvInputInfo inputInfo) {
1973            ServiceState serviceState = getServiceStateLocked(mComponent, mUserId);
1974            serviceState.mInputList.add(inputInfo);
1975            buildTvInputListLocked(mUserId);
1976        }
1977
1978        @Override
1979        public void addHardwareTvInput(int deviceId, TvInputInfo inputInfo) {
1980            ensureHardwarePermission();
1981            ensureValidInput(inputInfo);
1982            synchronized (mLock) {
1983                mTvInputHardwareManager.addHardwareTvInput(deviceId, inputInfo);
1984                addTvInputLocked(inputInfo);
1985            }
1986        }
1987
1988        @Override
1989        public void addHdmiCecTvInput(int logicalAddress, TvInputInfo inputInfo) {
1990            ensureHardwarePermission();
1991            ensureValidInput(inputInfo);
1992            synchronized (mLock) {
1993                mTvInputHardwareManager.addHdmiCecTvInput(logicalAddress, inputInfo);
1994                addTvInputLocked(inputInfo);
1995            }
1996        }
1997
1998        @Override
1999        public void removeTvInput(String inputId) {
2000            ensureHardwarePermission();
2001            synchronized (mLock) {
2002                ServiceState serviceState = getServiceStateLocked(mComponent, mUserId);
2003                boolean removed = false;
2004                for (Iterator<TvInputInfo> it = serviceState.mInputList.iterator();
2005                        it.hasNext(); ) {
2006                    if (it.next().getId().equals(inputId)) {
2007                        it.remove();
2008                        removed = true;
2009                        break;
2010                    }
2011                }
2012                if (removed) {
2013                    buildTvInputListLocked(mUserId);
2014                    mTvInputHardwareManager.removeTvInput(inputId);
2015                } else {
2016                    Slog.e(TAG, "TvInputInfo with inputId=" + inputId + " not found.");
2017                }
2018            }
2019        }
2020    }
2021
2022    private final class LogHandler extends Handler {
2023        private static final int MSG_OPEN_ENTRY = 1;
2024        private static final int MSG_UPDATE_ENTRY = 2;
2025        private static final int MSG_CLOSE_ENTRY = 3;
2026
2027        public LogHandler(Looper looper) {
2028            super(looper);
2029        }
2030
2031        @Override
2032        public void handleMessage(Message msg) {
2033            switch (msg.what) {
2034                case MSG_OPEN_ENTRY: {
2035                    SomeArgs args = (SomeArgs) msg.obj;
2036                    Uri uri = (Uri) args.arg1;
2037                    long channelId = (long) args.arg2;
2038                    long time = (long) args.arg3;
2039                    onOpenEntry(uri, channelId, time);
2040                    args.recycle();
2041                    return;
2042                }
2043                case MSG_UPDATE_ENTRY: {
2044                    SomeArgs args = (SomeArgs) msg.obj;
2045                    Uri uri = (Uri) args.arg1;
2046                    long channelId = (long) args.arg2;
2047                    long time = (long) args.arg3;
2048                    onUpdateEntry(uri, channelId, time);
2049                    args.recycle();
2050                    return;
2051                }
2052                case MSG_CLOSE_ENTRY: {
2053                    SomeArgs args = (SomeArgs) msg.obj;
2054                    Uri uri = (Uri) args.arg1;
2055                    long time = (long) args.arg2;
2056                    onCloseEntry(uri, time);
2057                    args.recycle();
2058                    return;
2059                }
2060                default: {
2061                    Slog.w(TAG, "Unhandled message code: " + msg.what);
2062                    return;
2063                }
2064            }
2065        }
2066
2067        private void onOpenEntry(Uri uri, long channelId, long watchStarttime) {
2068            String[] projection = {
2069                    TvContract.Programs.COLUMN_TITLE,
2070                    TvContract.Programs.COLUMN_START_TIME_UTC_MILLIS,
2071                    TvContract.Programs.COLUMN_END_TIME_UTC_MILLIS,
2072                    TvContract.Programs.COLUMN_SHORT_DESCRIPTION
2073            };
2074            String selection = TvContract.Programs.COLUMN_CHANNEL_ID + "=? AND "
2075                    + TvContract.Programs.COLUMN_START_TIME_UTC_MILLIS + "<=? AND "
2076                    + TvContract.Programs.COLUMN_END_TIME_UTC_MILLIS + ">?";
2077            String[] selectionArgs = {
2078                    String.valueOf(channelId),
2079                    String.valueOf(watchStarttime),
2080                    String.valueOf(watchStarttime)
2081            };
2082            String sortOrder = TvContract.Programs.COLUMN_START_TIME_UTC_MILLIS + " ASC";
2083            Cursor cursor = null;
2084            try {
2085                cursor = mContentResolver.query(TvContract.Programs.CONTENT_URI, projection,
2086                        selection, selectionArgs, sortOrder);
2087                if (cursor != null && cursor.moveToNext()) {
2088                    ContentValues values = new ContentValues();
2089                    values.put(TvContract.WatchedPrograms.COLUMN_TITLE, cursor.getString(0));
2090                    values.put(TvContract.WatchedPrograms.COLUMN_START_TIME_UTC_MILLIS,
2091                            cursor.getLong(1));
2092                    long endTime = cursor.getLong(2);
2093                    values.put(TvContract.WatchedPrograms.COLUMN_END_TIME_UTC_MILLIS, endTime);
2094                    values.put(TvContract.WatchedPrograms.COLUMN_DESCRIPTION, cursor.getString(3));
2095                    mContentResolver.update(uri, values, null, null);
2096
2097                    // Schedule an update when the current program ends.
2098                    SomeArgs args = SomeArgs.obtain();
2099                    args.arg1 = uri;
2100                    args.arg2 = channelId;
2101                    args.arg3 = endTime;
2102                    Message msg = obtainMessage(LogHandler.MSG_UPDATE_ENTRY, args);
2103                    sendMessageDelayed(msg, endTime - System.currentTimeMillis());
2104                }
2105            } finally {
2106                if (cursor != null) {
2107                    cursor.close();
2108                }
2109            }
2110        }
2111
2112        private void onUpdateEntry(Uri uri, long channelId, long time) {
2113            String[] projection = {
2114                    TvContract.WatchedPrograms.COLUMN_WATCH_START_TIME_UTC_MILLIS,
2115                    TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS,
2116                    TvContract.WatchedPrograms.COLUMN_TITLE,
2117                    TvContract.WatchedPrograms.COLUMN_START_TIME_UTC_MILLIS,
2118                    TvContract.WatchedPrograms.COLUMN_END_TIME_UTC_MILLIS,
2119                    TvContract.WatchedPrograms.COLUMN_DESCRIPTION
2120            };
2121            Cursor cursor = null;
2122            try {
2123                cursor = mContentResolver.query(uri, projection, null, null, null);
2124                if (cursor != null && cursor.moveToNext()) {
2125                    long watchStartTime = cursor.getLong(0);
2126                    long watchEndTime = cursor.getLong(1);
2127                    String title = cursor.getString(2);
2128                    long startTime = cursor.getLong(3);
2129                    long endTime = cursor.getLong(4);
2130                    String description = cursor.getString(5);
2131
2132                    // Do nothing if the current log entry is already closed.
2133                    if (watchEndTime > 0) {
2134                        return;
2135                    }
2136
2137                    // The current program has just ended. Create a (complete) log entry off the
2138                    // current entry.
2139                    ContentValues values = new ContentValues();
2140                    values.put(TvContract.WatchedPrograms.COLUMN_WATCH_START_TIME_UTC_MILLIS,
2141                            watchStartTime);
2142                    values.put(TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS, time);
2143                    values.put(TvContract.WatchedPrograms.COLUMN_CHANNEL_ID, channelId);
2144                    values.put(TvContract.WatchedPrograms.COLUMN_TITLE, title);
2145                    values.put(TvContract.WatchedPrograms.COLUMN_START_TIME_UTC_MILLIS, startTime);
2146                    values.put(TvContract.WatchedPrograms.COLUMN_END_TIME_UTC_MILLIS, endTime);
2147                    values.put(TvContract.WatchedPrograms.COLUMN_DESCRIPTION, description);
2148                    mContentResolver.insert(TvContract.WatchedPrograms.CONTENT_URI, values);
2149                }
2150            } finally {
2151                if (cursor != null) {
2152                    cursor.close();
2153                }
2154            }
2155            // Re-open the current log entry with the next program information.
2156            onOpenEntry(uri, channelId, time);
2157        }
2158
2159        private void onCloseEntry(Uri uri, long watchEndTime) {
2160            ContentValues values = new ContentValues();
2161            values.put(TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS, watchEndTime);
2162            mContentResolver.update(uri, values, null, null);
2163        }
2164    }
2165
2166    final class HardwareListener implements TvInputHardwareManager.Listener {
2167        @Override
2168        public void onStateChanged(String inputId, int state) {
2169            synchronized (mLock) {
2170                setStateLocked(inputId, state, mCurrentUserId);
2171            }
2172        }
2173
2174        @Override
2175        public void onHardwareDeviceAdded(TvInputHardwareInfo info) {
2176            synchronized (mLock) {
2177                UserState userState = getUserStateLocked(mCurrentUserId);
2178                // Broadcast the event to all hardware inputs.
2179                for (ServiceState serviceState : userState.serviceStateMap.values()) {
2180                    if (!serviceState.mIsHardware || serviceState.mService == null) continue;
2181                    try {
2182                        serviceState.mService.notifyHardwareAdded(info);
2183                    } catch (RemoteException e) {
2184                        Slog.e(TAG, "error in notifyHardwareAdded", e);
2185                    }
2186                }
2187            }
2188        }
2189
2190        @Override
2191        public void onHardwareDeviceRemoved(TvInputHardwareInfo info) {
2192            synchronized (mLock) {
2193                UserState userState = getUserStateLocked(mCurrentUserId);
2194                // Broadcast the event to all hardware inputs.
2195                for (ServiceState serviceState : userState.serviceStateMap.values()) {
2196                    if (!serviceState.mIsHardware || serviceState.mService == null) continue;
2197                    try {
2198                        serviceState.mService.notifyHardwareRemoved(info);
2199                    } catch (RemoteException e) {
2200                        Slog.e(TAG, "error in notifyHardwareRemoved", e);
2201                    }
2202                }
2203            }
2204        }
2205
2206        @Override
2207        public void onHdmiCecDeviceAdded(HdmiDeviceInfo cecDeviceInfo) {
2208            synchronized (mLock) {
2209                UserState userState = getUserStateLocked(mCurrentUserId);
2210                // Broadcast the event to all hardware inputs.
2211                for (ServiceState serviceState : userState.serviceStateMap.values()) {
2212                    if (!serviceState.mIsHardware || serviceState.mService == null) continue;
2213                    try {
2214                        serviceState.mService.notifyHdmiCecDeviceAdded(cecDeviceInfo);
2215                    } catch (RemoteException e) {
2216                        Slog.e(TAG, "error in notifyHdmiCecDeviceAdded", e);
2217                    }
2218                }
2219            }
2220        }
2221
2222        @Override
2223        public void onHdmiCecDeviceRemoved(HdmiDeviceInfo cecDeviceInfo) {
2224            synchronized (mLock) {
2225                UserState userState = getUserStateLocked(mCurrentUserId);
2226                // Broadcast the event to all hardware inputs.
2227                for (ServiceState serviceState : userState.serviceStateMap.values()) {
2228                    if (!serviceState.mIsHardware || serviceState.mService == null) continue;
2229                    try {
2230                        serviceState.mService.notifyHdmiCecDeviceRemoved(cecDeviceInfo);
2231                    } catch (RemoteException e) {
2232                        Slog.e(TAG, "error in notifyHdmiCecDeviceRemoved", e);
2233                    }
2234                }
2235            }
2236        }
2237    }
2238}
2239