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