TvInputManagerService.java revision 5d0ec89d55f0e986a0704ce1c8ea5c1a604c4cb2
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 if (mContext.checkCallingPermission( 1023 android.Manifest.permission.MODIFY_PARENTAL_CONTROLS) 1024 != PackageManager.PERMISSION_GRANTED) { 1025 throw new SecurityException( 1026 "The caller does not have parental controls permission"); 1027 } 1028 } 1029 1030 @Override 1031 public void createSession(final ITvInputClient client, final String inputId, 1032 int seq, int userId) { 1033 final int callingUid = Binder.getCallingUid(); 1034 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1035 userId, "createSession"); 1036 final long identity = Binder.clearCallingIdentity(); 1037 try { 1038 synchronized (mLock) { 1039 UserState userState = getUserStateLocked(resolvedUserId); 1040 TvInputInfo info = userState.inputMap.get(inputId).mInfo; 1041 ServiceState serviceState = userState.serviceStateMap.get(info.getComponent()); 1042 if (serviceState == null) { 1043 serviceState = new ServiceState(info.getComponent(), resolvedUserId); 1044 userState.serviceStateMap.put(info.getComponent(), serviceState); 1045 } 1046 // Send a null token immediately while reconnecting. 1047 if (serviceState.mReconnecting == true) { 1048 sendSessionTokenToClientLocked(client, inputId, null, null, seq); 1049 return; 1050 } 1051 1052 // Create a new session token and a session state. 1053 IBinder sessionToken = new Binder(); 1054 SessionState sessionState = new SessionState(sessionToken, info, client, 1055 seq, callingUid, resolvedUserId); 1056 1057 // Add them to the global session state map of the current user. 1058 userState.sessionStateMap.put(sessionToken, sessionState); 1059 1060 // Also, add them to the session state map of the current service. 1061 serviceState.mSessionTokens.add(sessionToken); 1062 1063 if (serviceState.mService != null) { 1064 createSessionInternalLocked(serviceState.mService, sessionToken, 1065 resolvedUserId); 1066 } else { 1067 updateServiceConnectionLocked(info.getComponent(), resolvedUserId); 1068 } 1069 } 1070 } finally { 1071 Binder.restoreCallingIdentity(identity); 1072 } 1073 } 1074 1075 @Override 1076 public void releaseSession(IBinder sessionToken, int userId) { 1077 if (DEBUG) { 1078 Slog.d(TAG, "releaseSession(): " + sessionToken); 1079 } 1080 final int callingUid = Binder.getCallingUid(); 1081 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1082 userId, "releaseSession"); 1083 final long identity = Binder.clearCallingIdentity(); 1084 try { 1085 synchronized (mLock) { 1086 releaseSessionLocked(sessionToken, callingUid, resolvedUserId); 1087 } 1088 } finally { 1089 Binder.restoreCallingIdentity(identity); 1090 } 1091 } 1092 1093 @Override 1094 public void setMainSession(IBinder sessionToken, int userId) { 1095 if (DEBUG) { 1096 Slog.d(TAG, "setMainSession(): " + sessionToken); 1097 } 1098 final int callingUid = Binder.getCallingUid(); 1099 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1100 userId, "setMainSession"); 1101 final long identity = Binder.clearCallingIdentity(); 1102 try { 1103 synchronized (mLock) { 1104 UserState userState = getUserStateLocked(resolvedUserId); 1105 if (userState.mainSessionToken == sessionToken) { 1106 return; 1107 } 1108 if (DEBUG) { 1109 Slog.d(TAG, "mainSessionToken=" + sessionToken); 1110 } 1111 IBinder oldMainSessionToken = userState.mainSessionToken; 1112 userState.mainSessionToken = sessionToken; 1113 1114 // Inform the new main session first. 1115 // See {@link TvInputService.Session#onSetMain}. 1116 if (sessionToken != null) { 1117 setMainLocked(sessionToken, true, callingUid, userId); 1118 } 1119 if (oldMainSessionToken != null) { 1120 setMainLocked(oldMainSessionToken, false, Process.SYSTEM_UID, userId); 1121 } 1122 } 1123 } finally { 1124 Binder.restoreCallingIdentity(identity); 1125 } 1126 } 1127 1128 @Override 1129 public void setSurface(IBinder sessionToken, Surface surface, int userId) { 1130 final int callingUid = Binder.getCallingUid(); 1131 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1132 userId, "setSurface"); 1133 final long identity = Binder.clearCallingIdentity(); 1134 try { 1135 synchronized (mLock) { 1136 try { 1137 SessionState sessionState = getSessionStateLocked(sessionToken, callingUid, 1138 resolvedUserId); 1139 if (sessionState.mHardwareSessionToken == null) { 1140 getSessionLocked(sessionState).setSurface(surface); 1141 } else { 1142 getSessionLocked(sessionState.mHardwareSessionToken, 1143 Process.SYSTEM_UID, resolvedUserId).setSurface(surface); 1144 } 1145 } catch (RemoteException e) { 1146 Slog.e(TAG, "error in setSurface", e); 1147 } 1148 } 1149 } finally { 1150 if (surface != null) { 1151 // surface is not used in TvInputManagerService. 1152 surface.release(); 1153 } 1154 Binder.restoreCallingIdentity(identity); 1155 } 1156 } 1157 1158 @Override 1159 public void dispatchSurfaceChanged(IBinder sessionToken, int format, int width, 1160 int height, int userId) { 1161 final int callingUid = Binder.getCallingUid(); 1162 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1163 userId, "dispatchSurfaceChanged"); 1164 final long identity = Binder.clearCallingIdentity(); 1165 try { 1166 synchronized (mLock) { 1167 try { 1168 SessionState sessionState = getSessionStateLocked(sessionToken, callingUid, 1169 resolvedUserId); 1170 getSessionLocked(sessionState).dispatchSurfaceChanged(format, width, height); 1171 if (sessionState.mHardwareSessionToken != null) { 1172 getSessionLocked(sessionState.mHardwareSessionToken, Process.SYSTEM_UID, 1173 resolvedUserId).dispatchSurfaceChanged(format, width, height); 1174 } 1175 } catch (RemoteException e) { 1176 Slog.e(TAG, "error in dispatchSurfaceChanged", e); 1177 } 1178 } 1179 } finally { 1180 Binder.restoreCallingIdentity(identity); 1181 } 1182 } 1183 1184 @Override 1185 public void setVolume(IBinder sessionToken, float volume, int userId) { 1186 final float REMOTE_VOLUME_ON = 1.0f; 1187 final float REMOTE_VOLUME_OFF = 0f; 1188 final int callingUid = Binder.getCallingUid(); 1189 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1190 userId, "setVolume"); 1191 final long identity = Binder.clearCallingIdentity(); 1192 try { 1193 synchronized (mLock) { 1194 try { 1195 SessionState sessionState = getSessionStateLocked(sessionToken, callingUid, 1196 resolvedUserId); 1197 getSessionLocked(sessionState).setVolume(volume); 1198 if (sessionState.mHardwareSessionToken != null) { 1199 // Here, we let the hardware session know only whether volume is on or 1200 // off to prevent that the volume is controlled in the both side. 1201 getSessionLocked(sessionState.mHardwareSessionToken, 1202 Process.SYSTEM_UID, resolvedUserId).setVolume((volume > 0.0f) 1203 ? REMOTE_VOLUME_ON : REMOTE_VOLUME_OFF); 1204 } 1205 } catch (RemoteException e) { 1206 Slog.e(TAG, "error in setVolume", e); 1207 } 1208 } 1209 } finally { 1210 Binder.restoreCallingIdentity(identity); 1211 } 1212 } 1213 1214 @Override 1215 public void tune(IBinder sessionToken, final Uri channelUri, Bundle params, int userId) { 1216 final int callingUid = Binder.getCallingUid(); 1217 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1218 userId, "tune"); 1219 final long identity = Binder.clearCallingIdentity(); 1220 try { 1221 synchronized (mLock) { 1222 try { 1223 getSessionLocked(sessionToken, callingUid, resolvedUserId).tune( 1224 channelUri, params); 1225 if (TvContract.isChannelUriForPassthroughInput(channelUri)) { 1226 // Do not log the watch history for passthrough inputs. 1227 return; 1228 } 1229 1230 UserState userState = getUserStateLocked(resolvedUserId); 1231 SessionState sessionState = userState.sessionStateMap.get(sessionToken); 1232 1233 // Log the start of watch. 1234 SomeArgs args = SomeArgs.obtain(); 1235 args.arg1 = sessionState.mInfo.getComponent().getPackageName(); 1236 args.arg2 = System.currentTimeMillis(); 1237 args.arg3 = ContentUris.parseId(channelUri); 1238 args.arg4 = params; 1239 args.arg5 = sessionToken; 1240 mWatchLogHandler.obtainMessage(WatchLogHandler.MSG_LOG_WATCH_START, args) 1241 .sendToTarget(); 1242 } catch (RemoteException e) { 1243 Slog.e(TAG, "error in tune", e); 1244 return; 1245 } 1246 } 1247 } finally { 1248 Binder.restoreCallingIdentity(identity); 1249 } 1250 } 1251 1252 @Override 1253 public void requestUnblockContent( 1254 IBinder sessionToken, String unblockedRating, int userId) { 1255 final int callingUid = Binder.getCallingUid(); 1256 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1257 userId, "unblockContent"); 1258 final long identity = Binder.clearCallingIdentity(); 1259 try { 1260 synchronized (mLock) { 1261 try { 1262 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1263 .requestUnblockContent(unblockedRating); 1264 } catch (RemoteException e) { 1265 Slog.e(TAG, "error in unblockContent", e); 1266 } 1267 } 1268 } finally { 1269 Binder.restoreCallingIdentity(identity); 1270 } 1271 } 1272 1273 @Override 1274 public void setCaptionEnabled(IBinder sessionToken, boolean enabled, int userId) { 1275 final int callingUid = Binder.getCallingUid(); 1276 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1277 userId, "setCaptionEnabled"); 1278 final long identity = Binder.clearCallingIdentity(); 1279 try { 1280 synchronized (mLock) { 1281 try { 1282 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1283 .setCaptionEnabled(enabled); 1284 } catch (RemoteException e) { 1285 Slog.e(TAG, "error in setCaptionEnabled", e); 1286 } 1287 } 1288 } finally { 1289 Binder.restoreCallingIdentity(identity); 1290 } 1291 } 1292 1293 @Override 1294 public void selectTrack(IBinder sessionToken, int type, String trackId, int userId) { 1295 final int callingUid = Binder.getCallingUid(); 1296 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1297 userId, "selectTrack"); 1298 final long identity = Binder.clearCallingIdentity(); 1299 try { 1300 synchronized (mLock) { 1301 try { 1302 getSessionLocked(sessionToken, callingUid, resolvedUserId).selectTrack( 1303 type, trackId); 1304 } catch (RemoteException e) { 1305 Slog.e(TAG, "error in selectTrack", e); 1306 } 1307 } 1308 } finally { 1309 Binder.restoreCallingIdentity(identity); 1310 } 1311 } 1312 1313 @Override 1314 public void sendAppPrivateCommand(IBinder sessionToken, String command, Bundle data, 1315 int userId) { 1316 final int callingUid = Binder.getCallingUid(); 1317 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1318 userId, "sendAppPrivateCommand"); 1319 final long identity = Binder.clearCallingIdentity(); 1320 try { 1321 synchronized (mLock) { 1322 try { 1323 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1324 .appPrivateCommand(command, data); 1325 } catch (RemoteException e) { 1326 Slog.e(TAG, "error in sendAppPrivateCommand", e); 1327 } 1328 } 1329 } finally { 1330 Binder.restoreCallingIdentity(identity); 1331 } 1332 } 1333 1334 @Override 1335 public void createOverlayView(IBinder sessionToken, IBinder windowToken, Rect frame, 1336 int userId) { 1337 final int callingUid = Binder.getCallingUid(); 1338 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1339 userId, "createOverlayView"); 1340 final long identity = Binder.clearCallingIdentity(); 1341 try { 1342 synchronized (mLock) { 1343 try { 1344 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1345 .createOverlayView(windowToken, frame); 1346 } catch (RemoteException e) { 1347 Slog.e(TAG, "error in createOverlayView", e); 1348 } 1349 } 1350 } finally { 1351 Binder.restoreCallingIdentity(identity); 1352 } 1353 } 1354 1355 @Override 1356 public void relayoutOverlayView(IBinder sessionToken, Rect frame, int userId) { 1357 final int callingUid = Binder.getCallingUid(); 1358 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1359 userId, "relayoutOverlayView"); 1360 final long identity = Binder.clearCallingIdentity(); 1361 try { 1362 synchronized (mLock) { 1363 try { 1364 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1365 .relayoutOverlayView(frame); 1366 } catch (RemoteException e) { 1367 Slog.e(TAG, "error in relayoutOverlayView", e); 1368 } 1369 } 1370 } finally { 1371 Binder.restoreCallingIdentity(identity); 1372 } 1373 } 1374 1375 @Override 1376 public void removeOverlayView(IBinder sessionToken, int userId) { 1377 final int callingUid = Binder.getCallingUid(); 1378 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1379 userId, "removeOverlayView"); 1380 final long identity = Binder.clearCallingIdentity(); 1381 try { 1382 synchronized (mLock) { 1383 try { 1384 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1385 .removeOverlayView(); 1386 } catch (RemoteException e) { 1387 Slog.e(TAG, "error in removeOverlayView", e); 1388 } 1389 } 1390 } finally { 1391 Binder.restoreCallingIdentity(identity); 1392 } 1393 } 1394 1395 @Override 1396 public List<TvInputHardwareInfo> getHardwareList() throws RemoteException { 1397 if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE) 1398 != PackageManager.PERMISSION_GRANTED) { 1399 return null; 1400 } 1401 1402 final long identity = Binder.clearCallingIdentity(); 1403 try { 1404 return mTvInputHardwareManager.getHardwareList(); 1405 } finally { 1406 Binder.restoreCallingIdentity(identity); 1407 } 1408 } 1409 1410 @Override 1411 public ITvInputHardware acquireTvInputHardware(int deviceId, 1412 ITvInputHardwareCallback callback, TvInputInfo info, int userId) 1413 throws RemoteException { 1414 if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE) 1415 != PackageManager.PERMISSION_GRANTED) { 1416 return null; 1417 } 1418 1419 final long identity = Binder.clearCallingIdentity(); 1420 final int callingUid = Binder.getCallingUid(); 1421 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1422 userId, "acquireTvInputHardware"); 1423 try { 1424 return mTvInputHardwareManager.acquireHardware( 1425 deviceId, callback, info, callingUid, resolvedUserId); 1426 } finally { 1427 Binder.restoreCallingIdentity(identity); 1428 } 1429 } 1430 1431 @Override 1432 public void releaseTvInputHardware(int deviceId, ITvInputHardware hardware, int userId) 1433 throws RemoteException { 1434 if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE) 1435 != PackageManager.PERMISSION_GRANTED) { 1436 return; 1437 } 1438 1439 final long identity = Binder.clearCallingIdentity(); 1440 final int callingUid = Binder.getCallingUid(); 1441 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1442 userId, "releaseTvInputHardware"); 1443 try { 1444 mTvInputHardwareManager.releaseHardware( 1445 deviceId, hardware, callingUid, resolvedUserId); 1446 } finally { 1447 Binder.restoreCallingIdentity(identity); 1448 } 1449 } 1450 1451 @Override 1452 public List<TvStreamConfig> getAvailableTvStreamConfigList(String inputId, int userId) 1453 throws RemoteException { 1454 if (mContext.checkCallingPermission( 1455 android.Manifest.permission.CAPTURE_TV_INPUT) 1456 != PackageManager.PERMISSION_GRANTED) { 1457 throw new SecurityException("Requires CAPTURE_TV_INPUT permission"); 1458 } 1459 1460 final long identity = Binder.clearCallingIdentity(); 1461 final int callingUid = Binder.getCallingUid(); 1462 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1463 userId, "getAvailableTvStreamConfigList"); 1464 try { 1465 return mTvInputHardwareManager.getAvailableTvStreamConfigList( 1466 inputId, callingUid, resolvedUserId); 1467 } finally { 1468 Binder.restoreCallingIdentity(identity); 1469 } 1470 } 1471 1472 @Override 1473 public boolean captureFrame(String inputId, Surface surface, TvStreamConfig config, 1474 int userId) 1475 throws RemoteException { 1476 if (mContext.checkCallingPermission( 1477 android.Manifest.permission.CAPTURE_TV_INPUT) 1478 != PackageManager.PERMISSION_GRANTED) { 1479 throw new SecurityException("Requires CAPTURE_TV_INPUT permission"); 1480 } 1481 1482 final long identity = Binder.clearCallingIdentity(); 1483 final int callingUid = Binder.getCallingUid(); 1484 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1485 userId, "captureFrame"); 1486 try { 1487 String hardwareInputId = null; 1488 synchronized (mLock) { 1489 UserState userState = getUserStateLocked(resolvedUserId); 1490 if (userState.inputMap.get(inputId) == null) { 1491 Slog.e(TAG, "Input not found for " + inputId); 1492 return false; 1493 } 1494 for (SessionState sessionState : userState.sessionStateMap.values()) { 1495 if (sessionState.mInfo.getId().equals(inputId) 1496 && sessionState.mHardwareSessionToken != null) { 1497 hardwareInputId = userState.sessionStateMap.get( 1498 sessionState.mHardwareSessionToken).mInfo.getId(); 1499 break; 1500 } 1501 } 1502 } 1503 return mTvInputHardwareManager.captureFrame( 1504 (hardwareInputId != null) ? hardwareInputId : inputId, 1505 surface, config, callingUid, resolvedUserId); 1506 } finally { 1507 Binder.restoreCallingIdentity(identity); 1508 } 1509 } 1510 1511 @Override 1512 public boolean isSingleSessionActive(int userId) throws RemoteException { 1513 final long identity = Binder.clearCallingIdentity(); 1514 final int callingUid = Binder.getCallingUid(); 1515 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1516 userId, "isSingleSessionActive"); 1517 try { 1518 synchronized (mLock) { 1519 UserState userState = getUserStateLocked(resolvedUserId); 1520 if (userState.sessionStateMap.size() == 1) { 1521 return true; 1522 } 1523 else if (userState.sessionStateMap.size() == 2) { 1524 SessionState[] sessionStates = userState.sessionStateMap.values().toArray( 1525 new SessionState[0]); 1526 // Check if there is a wrapper input. 1527 if (sessionStates[0].mHardwareSessionToken != null 1528 || sessionStates[1].mHardwareSessionToken != null) { 1529 return true; 1530 } 1531 } 1532 return false; 1533 } 1534 } finally { 1535 Binder.restoreCallingIdentity(identity); 1536 } 1537 } 1538 1539 @Override 1540 @SuppressWarnings("resource") 1541 protected void dump(FileDescriptor fd, final PrintWriter writer, String[] args) { 1542 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " "); 1543 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 1544 != PackageManager.PERMISSION_GRANTED) { 1545 pw.println("Permission Denial: can't dump TvInputManager from pid=" 1546 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()); 1547 return; 1548 } 1549 1550 synchronized (mLock) { 1551 pw.println("User Ids (Current user: " + mCurrentUserId + "):"); 1552 pw.increaseIndent(); 1553 for (int i = 0; i < mUserStates.size(); i++) { 1554 int userId = mUserStates.keyAt(i); 1555 pw.println(Integer.valueOf(userId)); 1556 } 1557 pw.decreaseIndent(); 1558 1559 for (int i = 0; i < mUserStates.size(); i++) { 1560 int userId = mUserStates.keyAt(i); 1561 UserState userState = getUserStateLocked(userId); 1562 pw.println("UserState (" + userId + "):"); 1563 pw.increaseIndent(); 1564 1565 pw.println("inputMap: inputId -> TvInputState"); 1566 pw.increaseIndent(); 1567 for (Map.Entry<String, TvInputState> entry: userState.inputMap.entrySet()) { 1568 pw.println(entry.getKey() + ": " + entry.getValue()); 1569 } 1570 pw.decreaseIndent(); 1571 1572 pw.println("packageSet:"); 1573 pw.increaseIndent(); 1574 for (String packageName : userState.packageSet) { 1575 pw.println(packageName); 1576 } 1577 pw.decreaseIndent(); 1578 1579 pw.println("clientStateMap: ITvInputClient -> ClientState"); 1580 pw.increaseIndent(); 1581 for (Map.Entry<IBinder, ClientState> entry : 1582 userState.clientStateMap.entrySet()) { 1583 ClientState client = entry.getValue(); 1584 pw.println(entry.getKey() + ": " + client); 1585 1586 pw.increaseIndent(); 1587 1588 pw.println("mSessionTokens:"); 1589 pw.increaseIndent(); 1590 for (IBinder token : client.mSessionTokens) { 1591 pw.println("" + token); 1592 } 1593 pw.decreaseIndent(); 1594 1595 pw.println("mClientTokens: " + client.mClientToken); 1596 pw.println("mUserId: " + client.mUserId); 1597 1598 pw.decreaseIndent(); 1599 } 1600 pw.decreaseIndent(); 1601 1602 pw.println("serviceStateMap: ComponentName -> ServiceState"); 1603 pw.increaseIndent(); 1604 for (Map.Entry<ComponentName, ServiceState> entry : 1605 userState.serviceStateMap.entrySet()) { 1606 ServiceState service = entry.getValue(); 1607 pw.println(entry.getKey() + ": " + service); 1608 1609 pw.increaseIndent(); 1610 1611 pw.println("mSessionTokens:"); 1612 pw.increaseIndent(); 1613 for (IBinder token : service.mSessionTokens) { 1614 pw.println("" + token); 1615 } 1616 pw.decreaseIndent(); 1617 1618 pw.println("mService: " + service.mService); 1619 pw.println("mCallback: " + service.mCallback); 1620 pw.println("mBound: " + service.mBound); 1621 pw.println("mReconnecting: " + service.mReconnecting); 1622 1623 pw.decreaseIndent(); 1624 } 1625 pw.decreaseIndent(); 1626 1627 pw.println("sessionStateMap: ITvInputSession -> SessionState"); 1628 pw.increaseIndent(); 1629 for (Map.Entry<IBinder, SessionState> entry : 1630 userState.sessionStateMap.entrySet()) { 1631 SessionState session = entry.getValue(); 1632 pw.println(entry.getKey() + ": " + session); 1633 1634 pw.increaseIndent(); 1635 pw.println("mInfo: " + session.mInfo); 1636 pw.println("mClient: " + session.mClient); 1637 pw.println("mSeq: " + session.mSeq); 1638 pw.println("mCallingUid: " + session.mCallingUid); 1639 pw.println("mUserId: " + session.mUserId); 1640 pw.println("mSessionToken: " + session.mSessionToken); 1641 pw.println("mSession: " + session.mSession); 1642 pw.println("mLogUri: " + session.mLogUri); 1643 pw.println("mHardwareSessionToken: " + session.mHardwareSessionToken); 1644 pw.decreaseIndent(); 1645 } 1646 pw.decreaseIndent(); 1647 1648 pw.println("callbackSet:"); 1649 pw.increaseIndent(); 1650 for (ITvInputManagerCallback callback : userState.callbackSet) { 1651 pw.println(callback.toString()); 1652 } 1653 pw.decreaseIndent(); 1654 1655 pw.println("mainSessionToken: " + userState.mainSessionToken); 1656 pw.decreaseIndent(); 1657 } 1658 } 1659 } 1660 } 1661 1662 private static final class TvInputState { 1663 // A TvInputInfo object which represents the TV input. 1664 private TvInputInfo mInfo; 1665 1666 // The state of TV input. Connected by default. 1667 private int mState = INPUT_STATE_CONNECTED; 1668 1669 @Override 1670 public String toString() { 1671 return "mInfo: " + mInfo + "; mState: " + mState; 1672 } 1673 } 1674 1675 private static final class UserState { 1676 // A mapping from the TV input id to its TvInputState. 1677 private Map<String, TvInputState> inputMap = new HashMap<String, TvInputState>(); 1678 1679 // A set of all TV input packages. 1680 private final Set<String> packageSet = new HashSet<String>(); 1681 1682 // A set of all TV content rating system xml uris. 1683 private final Set<Uri> ratingSystemXmlUriSet = new HashSet<Uri>(); 1684 1685 // A mapping from the token of a client to its state. 1686 private final Map<IBinder, ClientState> clientStateMap = 1687 new HashMap<IBinder, ClientState>(); 1688 1689 // A mapping from the name of a TV input service to its state. 1690 private final Map<ComponentName, ServiceState> serviceStateMap = 1691 new HashMap<ComponentName, ServiceState>(); 1692 1693 // A mapping from the token of a TV input session to its state. 1694 private final Map<IBinder, SessionState> sessionStateMap = 1695 new HashMap<IBinder, SessionState>(); 1696 1697 // A set of callbacks. 1698 private final Set<ITvInputManagerCallback> callbackSet = 1699 new HashSet<ITvInputManagerCallback>(); 1700 1701 // The token of a "main" TV input session. 1702 private IBinder mainSessionToken = null; 1703 1704 // Persistent data store for all internal settings maintained by the TV input manager 1705 // service. 1706 private final PersistentDataStore persistentDataStore; 1707 1708 private UserState(Context context, int userId) { 1709 persistentDataStore = new PersistentDataStore(context, userId); 1710 } 1711 } 1712 1713 private final class ClientState implements IBinder.DeathRecipient { 1714 private final List<IBinder> mSessionTokens = new ArrayList<IBinder>(); 1715 1716 private IBinder mClientToken; 1717 private final int mUserId; 1718 1719 ClientState(IBinder clientToken, int userId) { 1720 mClientToken = clientToken; 1721 mUserId = userId; 1722 } 1723 1724 public boolean isEmpty() { 1725 return mSessionTokens.isEmpty(); 1726 } 1727 1728 @Override 1729 public void binderDied() { 1730 synchronized (mLock) { 1731 UserState userState = getUserStateLocked(mUserId); 1732 // DO NOT remove the client state of clientStateMap in this method. It will be 1733 // removed in releaseSessionLocked(). 1734 ClientState clientState = userState.clientStateMap.get(mClientToken); 1735 if (clientState != null) { 1736 while (clientState.mSessionTokens.size() > 0) { 1737 releaseSessionLocked( 1738 clientState.mSessionTokens.get(0), Process.SYSTEM_UID, mUserId); 1739 } 1740 } 1741 mClientToken = null; 1742 } 1743 } 1744 } 1745 1746 private final class ServiceState { 1747 private final List<IBinder> mSessionTokens = new ArrayList<IBinder>(); 1748 private final ServiceConnection mConnection; 1749 private final ComponentName mComponent; 1750 private final boolean mIsHardware; 1751 private final List<TvInputInfo> mInputList = new ArrayList<TvInputInfo>(); 1752 1753 private ITvInputService mService; 1754 private ServiceCallback mCallback; 1755 private boolean mBound; 1756 private boolean mReconnecting; 1757 1758 private ServiceState(ComponentName component, int userId) { 1759 mComponent = component; 1760 mConnection = new InputServiceConnection(component, userId); 1761 mIsHardware = hasHardwarePermission(mContext.getPackageManager(), mComponent); 1762 } 1763 } 1764 1765 private final class SessionState implements IBinder.DeathRecipient { 1766 private final TvInputInfo mInfo; 1767 private final ITvInputClient mClient; 1768 private final int mSeq; 1769 private final int mCallingUid; 1770 private final int mUserId; 1771 private final IBinder mSessionToken; 1772 private ITvInputSession mSession; 1773 private Uri mLogUri; 1774 // Not null if this session represents an external device connected to a hardware TV input. 1775 private IBinder mHardwareSessionToken; 1776 1777 private SessionState(IBinder sessionToken, TvInputInfo info, ITvInputClient client, 1778 int seq, int callingUid, int userId) { 1779 mSessionToken = sessionToken; 1780 mInfo = info; 1781 mClient = client; 1782 mSeq = seq; 1783 mCallingUid = callingUid; 1784 mUserId = userId; 1785 } 1786 1787 @Override 1788 public void binderDied() { 1789 synchronized (mLock) { 1790 mSession = null; 1791 if (mClient != null) { 1792 try { 1793 mClient.onSessionReleased(mSeq); 1794 } catch(RemoteException e) { 1795 Slog.e(TAG, "error in onSessionReleased", e); 1796 } 1797 } 1798 // If there are any other sessions based on this session, they should be released. 1799 UserState userState = getUserStateLocked(mUserId); 1800 for (SessionState sessionState : userState.sessionStateMap.values()) { 1801 if (mSessionToken == sessionState.mHardwareSessionToken) { 1802 releaseSessionLocked(sessionState.mSessionToken, Process.SYSTEM_UID, 1803 mUserId); 1804 try { 1805 sessionState.mClient.onSessionReleased(sessionState.mSeq); 1806 } catch (RemoteException e) { 1807 Slog.e(TAG, "error in onSessionReleased", e); 1808 } 1809 } 1810 } 1811 removeSessionStateLocked(mSessionToken, mUserId); 1812 } 1813 } 1814 } 1815 1816 private final class InputServiceConnection implements ServiceConnection { 1817 private final ComponentName mComponent; 1818 private final int mUserId; 1819 1820 private InputServiceConnection(ComponentName component, int userId) { 1821 mComponent = component; 1822 mUserId = userId; 1823 } 1824 1825 @Override 1826 public void onServiceConnected(ComponentName component, IBinder service) { 1827 if (DEBUG) { 1828 Slog.d(TAG, "onServiceConnected(component=" + component + ")"); 1829 } 1830 synchronized (mLock) { 1831 UserState userState = getUserStateLocked(mUserId); 1832 ServiceState serviceState = userState.serviceStateMap.get(mComponent); 1833 serviceState.mService = ITvInputService.Stub.asInterface(service); 1834 1835 // Register a callback, if we need to. 1836 if (serviceState.mIsHardware && serviceState.mCallback == null) { 1837 serviceState.mCallback = new ServiceCallback(mComponent, mUserId); 1838 try { 1839 serviceState.mService.registerCallback(serviceState.mCallback); 1840 } catch (RemoteException e) { 1841 Slog.e(TAG, "error in registerCallback", e); 1842 } 1843 } 1844 1845 // And create sessions, if any. 1846 for (IBinder sessionToken : serviceState.mSessionTokens) { 1847 createSessionInternalLocked(serviceState.mService, sessionToken, mUserId); 1848 } 1849 1850 for (TvInputState inputState : userState.inputMap.values()) { 1851 if (inputState.mInfo.getComponent().equals(component) 1852 && inputState.mState != INPUT_STATE_DISCONNECTED) { 1853 notifyInputStateChangedLocked(userState, inputState.mInfo.getId(), 1854 inputState.mState, null); 1855 } 1856 } 1857 1858 if (serviceState.mIsHardware) { 1859 List<TvInputHardwareInfo> hardwareInfoList = 1860 mTvInputHardwareManager.getHardwareList(); 1861 for (TvInputHardwareInfo hardwareInfo : hardwareInfoList) { 1862 try { 1863 serviceState.mService.notifyHardwareAdded(hardwareInfo); 1864 } catch (RemoteException e) { 1865 Slog.e(TAG, "error in notifyHardwareAdded", e); 1866 } 1867 } 1868 1869 List<HdmiDeviceInfo> deviceInfoList = 1870 mTvInputHardwareManager.getHdmiDeviceList(); 1871 for (HdmiDeviceInfo deviceInfo : deviceInfoList) { 1872 try { 1873 serviceState.mService.notifyHdmiDeviceAdded(deviceInfo); 1874 } catch (RemoteException e) { 1875 Slog.e(TAG, "error in notifyHdmiDeviceAdded", e); 1876 } 1877 } 1878 } 1879 } 1880 } 1881 1882 @Override 1883 public void onServiceDisconnected(ComponentName component) { 1884 if (DEBUG) { 1885 Slog.d(TAG, "onServiceDisconnected(component=" + component + ")"); 1886 } 1887 if (!mComponent.equals(component)) { 1888 throw new IllegalArgumentException("Mismatched ComponentName: " 1889 + mComponent + " (expected), " + component + " (actual)."); 1890 } 1891 synchronized (mLock) { 1892 UserState userState = getUserStateLocked(mUserId); 1893 ServiceState serviceState = userState.serviceStateMap.get(mComponent); 1894 if (serviceState != null) { 1895 serviceState.mReconnecting = true; 1896 serviceState.mBound = false; 1897 serviceState.mService = null; 1898 serviceState.mCallback = null; 1899 1900 // Send null tokens for not finishing create session events. 1901 for (IBinder sessionToken : serviceState.mSessionTokens) { 1902 SessionState sessionState = userState.sessionStateMap.get(sessionToken); 1903 if (sessionState.mSession == null) { 1904 removeSessionStateLocked(sessionToken, sessionState.mUserId); 1905 sendSessionTokenToClientLocked(sessionState.mClient, 1906 sessionState.mInfo.getId(), null, null, sessionState.mSeq); 1907 } 1908 } 1909 1910 for (TvInputState inputState : userState.inputMap.values()) { 1911 if (inputState.mInfo.getComponent().equals(component)) { 1912 notifyInputStateChangedLocked(userState, inputState.mInfo.getId(), 1913 INPUT_STATE_DISCONNECTED, null); 1914 } 1915 } 1916 updateServiceConnectionLocked(mComponent, mUserId); 1917 } 1918 } 1919 } 1920 } 1921 1922 private final class ServiceCallback extends ITvInputServiceCallback.Stub { 1923 private final ComponentName mComponent; 1924 private final int mUserId; 1925 1926 ServiceCallback(ComponentName component, int userId) { 1927 mComponent = component; 1928 mUserId = userId; 1929 } 1930 1931 private void ensureHardwarePermission() { 1932 if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE) 1933 != PackageManager.PERMISSION_GRANTED) { 1934 throw new SecurityException("The caller does not have hardware permission"); 1935 } 1936 } 1937 1938 private void ensureValidInput(TvInputInfo inputInfo) { 1939 if (inputInfo.getId() == null || !mComponent.equals(inputInfo.getComponent())) { 1940 throw new IllegalArgumentException("Invalid TvInputInfo"); 1941 } 1942 } 1943 1944 private void addTvInputLocked(TvInputInfo inputInfo) { 1945 ServiceState serviceState = getServiceStateLocked(mComponent, mUserId); 1946 serviceState.mInputList.add(inputInfo); 1947 buildTvInputListLocked(mUserId); 1948 } 1949 1950 @Override 1951 public void addHardwareTvInput(int deviceId, TvInputInfo inputInfo) { 1952 ensureHardwarePermission(); 1953 ensureValidInput(inputInfo); 1954 synchronized (mLock) { 1955 mTvInputHardwareManager.addHardwareTvInput(deviceId, inputInfo); 1956 addTvInputLocked(inputInfo); 1957 } 1958 } 1959 1960 @Override 1961 public void addHdmiTvInput(int id, TvInputInfo inputInfo) { 1962 ensureHardwarePermission(); 1963 ensureValidInput(inputInfo); 1964 synchronized (mLock) { 1965 mTvInputHardwareManager.addHdmiTvInput(id, inputInfo); 1966 addTvInputLocked(inputInfo); 1967 } 1968 } 1969 1970 @Override 1971 public void removeTvInput(String inputId) { 1972 ensureHardwarePermission(); 1973 synchronized (mLock) { 1974 ServiceState serviceState = getServiceStateLocked(mComponent, mUserId); 1975 boolean removed = false; 1976 for (Iterator<TvInputInfo> it = serviceState.mInputList.iterator(); 1977 it.hasNext(); ) { 1978 if (it.next().getId().equals(inputId)) { 1979 it.remove(); 1980 removed = true; 1981 break; 1982 } 1983 } 1984 if (removed) { 1985 buildTvInputListLocked(mUserId); 1986 mTvInputHardwareManager.removeTvInput(inputId); 1987 } else { 1988 Slog.e(TAG, "TvInputInfo with inputId=" + inputId + " not found."); 1989 } 1990 } 1991 } 1992 } 1993 1994 private final class WatchLogHandler extends Handler { 1995 // There are only two kinds of watch events that can happen on the system: 1996 // 1. The current TV input session is tuned to a new channel. 1997 // 2. The session is released for some reason. 1998 // The former indicates the end of the previous log entry, if any, followed by the start of 1999 // a new entry. The latter indicates the end of the most recent entry for the given session. 2000 // Here the system supplies the database the smallest set of information only that is 2001 // sufficient to consolidate the log entries while minimizing database operations in the 2002 // system service. 2003 private static final int MSG_LOG_WATCH_START = 1; 2004 private static final int MSG_LOG_WATCH_END = 2; 2005 2006 public WatchLogHandler(Looper looper) { 2007 super(looper); 2008 } 2009 2010 @Override 2011 public void handleMessage(Message msg) { 2012 switch (msg.what) { 2013 case MSG_LOG_WATCH_START: { 2014 SomeArgs args = (SomeArgs) msg.obj; 2015 String packageName = (String) args.arg1; 2016 long watchStartTime = (long) args.arg2; 2017 long channelId = (long) args.arg3; 2018 Bundle tuneParams = (Bundle) args.arg4; 2019 IBinder sessionToken = (IBinder) args.arg5; 2020 2021 ContentValues values = new ContentValues(); 2022 values.put(TvContract.WatchedPrograms.COLUMN_PACKAGE_NAME, packageName); 2023 values.put(TvContract.WatchedPrograms.COLUMN_WATCH_START_TIME_UTC_MILLIS, 2024 watchStartTime); 2025 values.put(TvContract.WatchedPrograms.COLUMN_CHANNEL_ID, channelId); 2026 if (tuneParams != null) { 2027 values.put(TvContract.WatchedPrograms.COLUMN_INTERNAL_TUNE_PARAMS, 2028 encodeTuneParams(tuneParams)); 2029 } 2030 values.put(TvContract.WatchedPrograms.COLUMN_INTERNAL_SESSION_TOKEN, 2031 sessionToken.toString()); 2032 2033 mContentResolver.insert(TvContract.WatchedPrograms.CONTENT_URI, values); 2034 args.recycle(); 2035 return; 2036 } 2037 case MSG_LOG_WATCH_END: { 2038 SomeArgs args = (SomeArgs) msg.obj; 2039 IBinder sessionToken = (IBinder) args.arg1; 2040 long watchEndTime = (long) args.arg2; 2041 2042 ContentValues values = new ContentValues(); 2043 values.put(TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS, 2044 watchEndTime); 2045 values.put(TvContract.WatchedPrograms.COLUMN_INTERNAL_SESSION_TOKEN, 2046 sessionToken.toString()); 2047 2048 mContentResolver.insert(TvContract.WatchedPrograms.CONTENT_URI, values); 2049 args.recycle(); 2050 return; 2051 } 2052 default: { 2053 Slog.w(TAG, "Unhandled message code: " + msg.what); 2054 return; 2055 } 2056 } 2057 } 2058 2059 private String encodeTuneParams(Bundle tuneParams) { 2060 StringBuilder builder = new StringBuilder(); 2061 Set<String> keySet = tuneParams.keySet(); 2062 Iterator<String> it = keySet.iterator(); 2063 while (it.hasNext()) { 2064 String key = it.next(); 2065 Object value = tuneParams.get(key); 2066 if (value == null) { 2067 continue; 2068 } 2069 builder.append(replaceEscapeCharacters(key)); 2070 builder.append("="); 2071 builder.append(replaceEscapeCharacters(value.toString())); 2072 if (it.hasNext()) { 2073 builder.append(", "); 2074 } 2075 } 2076 return builder.toString(); 2077 } 2078 2079 private String replaceEscapeCharacters(String src) { 2080 final char ESCAPE_CHARACTER = '%'; 2081 final String ENCODING_TARGET_CHARACTERS = "%=,"; 2082 StringBuilder builder = new StringBuilder(); 2083 for (char ch : src.toCharArray()) { 2084 if (ENCODING_TARGET_CHARACTERS.indexOf(ch) >= 0) { 2085 builder.append(ESCAPE_CHARACTER); 2086 } 2087 builder.append(ch); 2088 } 2089 return builder.toString(); 2090 } 2091 } 2092 2093 final class HardwareListener implements TvInputHardwareManager.Listener { 2094 @Override 2095 public void onStateChanged(String inputId, int state) { 2096 synchronized (mLock) { 2097 setStateLocked(inputId, state, mCurrentUserId); 2098 } 2099 } 2100 2101 @Override 2102 public void onHardwareDeviceAdded(TvInputHardwareInfo info) { 2103 synchronized (mLock) { 2104 UserState userState = getUserStateLocked(mCurrentUserId); 2105 // Broadcast the event to all hardware inputs. 2106 for (ServiceState serviceState : userState.serviceStateMap.values()) { 2107 if (!serviceState.mIsHardware || serviceState.mService == null) continue; 2108 try { 2109 serviceState.mService.notifyHardwareAdded(info); 2110 } catch (RemoteException e) { 2111 Slog.e(TAG, "error in notifyHardwareAdded", e); 2112 } 2113 } 2114 } 2115 } 2116 2117 @Override 2118 public void onHardwareDeviceRemoved(TvInputHardwareInfo info) { 2119 synchronized (mLock) { 2120 UserState userState = getUserStateLocked(mCurrentUserId); 2121 // Broadcast the event to all hardware inputs. 2122 for (ServiceState serviceState : userState.serviceStateMap.values()) { 2123 if (!serviceState.mIsHardware || serviceState.mService == null) continue; 2124 try { 2125 serviceState.mService.notifyHardwareRemoved(info); 2126 } catch (RemoteException e) { 2127 Slog.e(TAG, "error in notifyHardwareRemoved", e); 2128 } 2129 } 2130 } 2131 } 2132 2133 @Override 2134 public void onHdmiDeviceAdded(HdmiDeviceInfo deviceInfo) { 2135 synchronized (mLock) { 2136 UserState userState = getUserStateLocked(mCurrentUserId); 2137 // Broadcast the event to all hardware inputs. 2138 for (ServiceState serviceState : userState.serviceStateMap.values()) { 2139 if (!serviceState.mIsHardware || serviceState.mService == null) continue; 2140 try { 2141 serviceState.mService.notifyHdmiDeviceAdded(deviceInfo); 2142 } catch (RemoteException e) { 2143 Slog.e(TAG, "error in notifyHdmiDeviceAdded", e); 2144 } 2145 } 2146 } 2147 } 2148 2149 @Override 2150 public void onHdmiDeviceRemoved(HdmiDeviceInfo deviceInfo) { 2151 synchronized (mLock) { 2152 UserState userState = getUserStateLocked(mCurrentUserId); 2153 // Broadcast the event to all hardware inputs. 2154 for (ServiceState serviceState : userState.serviceStateMap.values()) { 2155 if (!serviceState.mIsHardware || serviceState.mService == null) continue; 2156 try { 2157 serviceState.mService.notifyHdmiDeviceRemoved(deviceInfo); 2158 } catch (RemoteException e) { 2159 Slog.e(TAG, "error in notifyHdmiDeviceRemoved", e); 2160 } 2161 } 2162 } 2163 } 2164 2165 @Override 2166 public void onHdmiDeviceUpdated(String inputId, HdmiDeviceInfo deviceInfo) { 2167 synchronized (mLock) { 2168 Integer state = null; 2169 switch (deviceInfo.getDevicePowerStatus()) { 2170 case HdmiControlManager.POWER_STATUS_ON: 2171 state = INPUT_STATE_CONNECTED; 2172 break; 2173 case HdmiControlManager.POWER_STATUS_STANDBY: 2174 case HdmiControlManager.POWER_STATUS_TRANSIENT_TO_ON: 2175 case HdmiControlManager.POWER_STATUS_TRANSIENT_TO_STANDBY: 2176 state = INPUT_STATE_CONNECTED_STANDBY; 2177 break; 2178 case HdmiControlManager.POWER_STATUS_UNKNOWN: 2179 default: 2180 state = null; 2181 break; 2182 } 2183 if (state != null) { 2184 setStateLocked(inputId, state.intValue(), mCurrentUserId); 2185 } 2186 } 2187 } 2188 } 2189} 2190