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