TvInputManagerService.java revision 0cb5244e52590214ddc16dd5fc1030b5baf04726
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; 21 22import android.annotation.Nullable; 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.ActivityInfo; 37import android.content.pm.PackageManager; 38import android.content.pm.PackageManager.NameNotFoundException; 39import android.content.pm.ResolveInfo; 40import android.content.pm.ServiceInfo; 41import android.graphics.Rect; 42import android.hardware.hdmi.HdmiControlManager; 43import android.hardware.hdmi.HdmiDeviceInfo; 44import android.media.PlaybackParams; 45import android.media.tv.DvbDeviceInfo; 46import android.media.tv.ITvInputClient; 47import android.media.tv.ITvInputHardware; 48import android.media.tv.ITvInputHardwareCallback; 49import android.media.tv.ITvInputManager; 50import android.media.tv.ITvInputManagerCallback; 51import android.media.tv.ITvInputService; 52import android.media.tv.ITvInputServiceCallback; 53import android.media.tv.ITvInputSession; 54import android.media.tv.ITvInputSessionCallback; 55import android.media.tv.TvContentRating; 56import android.media.tv.TvContentRatingSystemInfo; 57import android.media.tv.TvContract; 58import android.media.tv.TvInputHardwareInfo; 59import android.media.tv.TvInputInfo; 60import android.media.tv.TvInputManager; 61import android.media.tv.TvInputService; 62import android.media.tv.TvStreamConfig; 63import android.media.tv.TvTrackInfo; 64import android.net.Uri; 65import android.os.Binder; 66import android.os.Bundle; 67import android.os.Handler; 68import android.os.IBinder; 69import android.os.Looper; 70import android.os.Message; 71import android.os.ParcelFileDescriptor; 72import android.os.Process; 73import android.os.RemoteException; 74import android.os.UserHandle; 75import android.text.TextUtils; 76import android.util.Slog; 77import android.util.SparseArray; 78import android.view.InputChannel; 79import android.view.Surface; 80 81import com.android.internal.content.PackageMonitor; 82import com.android.internal.os.SomeArgs; 83import com.android.internal.util.IndentingPrintWriter; 84import com.android.server.IoThread; 85import com.android.server.SystemService; 86 87import org.xmlpull.v1.XmlPullParserException; 88 89import java.io.File; 90import java.io.FileDescriptor; 91import java.io.FileNotFoundException; 92import java.io.IOException; 93import java.io.PrintWriter; 94import java.util.ArrayList; 95import java.util.Arrays; 96import java.util.Collections; 97import java.util.HashMap; 98import java.util.HashSet; 99import java.util.Iterator; 100import java.util.List; 101import java.util.Map; 102import java.util.Set; 103import java.util.regex.Matcher; 104import java.util.regex.Pattern; 105 106/** This class provides a system service that manages television inputs. */ 107public final class TvInputManagerService extends SystemService { 108 private static final boolean DEBUG = false; 109 private static final String TAG = "TvInputManagerService"; 110 111 // Pattern for selecting the DVB frontend devices from the list of files in the /dev directory. 112 private static final Pattern sFrontEndDevicePattern = 113 Pattern.compile("^dvb([0-9]+)\\.frontend([0-9]+)$"); 114 115 private final Context mContext; 116 private final TvInputHardwareManager mTvInputHardwareManager; 117 118 // A global lock. 119 private final Object mLock = new Object(); 120 121 // ID of the current user. 122 private int mCurrentUserId = UserHandle.USER_SYSTEM; 123 124 // A map from user id to UserState. 125 private final SparseArray<UserState> mUserStates = new SparseArray<>(); 126 127 private final WatchLogHandler mWatchLogHandler; 128 129 public TvInputManagerService(Context context) { 130 super(context); 131 132 mContext = context; 133 mWatchLogHandler = new WatchLogHandler(mContext.getContentResolver(), 134 IoThread.get().getLooper()); 135 mTvInputHardwareManager = new TvInputHardwareManager(context, new HardwareListener()); 136 137 synchronized (mLock) { 138 getOrCreateUserStateLocked(mCurrentUserId); 139 } 140 } 141 142 @Override 143 public void onStart() { 144 publishBinderService(Context.TV_INPUT_SERVICE, new BinderService()); 145 } 146 147 @Override 148 public void onBootPhase(int phase) { 149 if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) { 150 registerBroadcastReceivers(); 151 } else if (phase == SystemService.PHASE_THIRD_PARTY_APPS_CAN_START) { 152 synchronized (mLock) { 153 buildTvInputListLocked(mCurrentUserId, null); 154 buildTvContentRatingSystemListLocked(mCurrentUserId); 155 } 156 } 157 mTvInputHardwareManager.onBootPhase(phase); 158 } 159 160 private void registerBroadcastReceivers() { 161 PackageMonitor monitor = new PackageMonitor() { 162 private void buildTvInputList(String[] packages) { 163 synchronized (mLock) { 164 buildTvInputListLocked(getChangingUserId(), packages); 165 buildTvContentRatingSystemListLocked(getChangingUserId()); 166 } 167 } 168 169 @Override 170 public void onPackageUpdateFinished(String packageName, int uid) { 171 if (DEBUG) Slog.d(TAG, "onPackageUpdateFinished(packageName=" + packageName + ")"); 172 // This callback is invoked when the TV input is reinstalled. 173 // In this case, isReplacing() always returns true. 174 buildTvInputList(new String[] { packageName }); 175 } 176 177 @Override 178 public void onPackagesAvailable(String[] packages) { 179 if (DEBUG) { 180 Slog.d(TAG, "onPackagesAvailable(packages=" + Arrays.toString(packages) + ")"); 181 } 182 // This callback is invoked when the media on which some packages exist become 183 // available. 184 if (isReplacing()) { 185 buildTvInputList(packages); 186 } 187 } 188 189 @Override 190 public void onPackagesUnavailable(String[] packages) { 191 // This callback is invoked when the media on which some packages exist become 192 // unavailable. 193 if (DEBUG) { 194 Slog.d(TAG, "onPackagesUnavailable(packages=" + Arrays.toString(packages) 195 + ")"); 196 } 197 if (isReplacing()) { 198 buildTvInputList(packages); 199 } 200 } 201 202 @Override 203 public void onSomePackagesChanged() { 204 // TODO: Use finer-grained methods(e.g. onPackageAdded, onPackageRemoved) to manage 205 // the TV inputs. 206 if (DEBUG) Slog.d(TAG, "onSomePackagesChanged()"); 207 if (isReplacing()) { 208 if (DEBUG) Slog.d(TAG, "Skipped building TV input list due to replacing"); 209 // When the package is updated, buildTvInputListLocked is called in other 210 // methods instead. 211 return; 212 } 213 buildTvInputList(null); 214 } 215 216 @Override 217 public boolean onPackageChanged(String packageName, int uid, String[] components) { 218 // The input list needs to be updated in any cases, regardless of whether 219 // it happened to the whole package or a specific component. Returning true so that 220 // the update can be handled in {@link #onSomePackagesChanged}. 221 return true; 222 } 223 224 @Override 225 public void onPackageRemoved(String packageName, int uid) { 226 synchronized (mLock) { 227 UserState userState = getOrCreateUserStateLocked(getChangingUserId()); 228 if (!userState.packageSet.contains(packageName)) { 229 // Not a TV input package. 230 return; 231 } 232 } 233 234 ArrayList<ContentProviderOperation> operations = new ArrayList<>(); 235 236 String selection = TvContract.BaseTvColumns.COLUMN_PACKAGE_NAME + "=?"; 237 String[] selectionArgs = { packageName }; 238 239 operations.add(ContentProviderOperation.newDelete(TvContract.Channels.CONTENT_URI) 240 .withSelection(selection, selectionArgs).build()); 241 operations.add(ContentProviderOperation.newDelete(TvContract.Programs.CONTENT_URI) 242 .withSelection(selection, selectionArgs).build()); 243 operations.add(ContentProviderOperation 244 .newDelete(TvContract.WatchedPrograms.CONTENT_URI) 245 .withSelection(selection, selectionArgs).build()); 246 247 ContentProviderResult[] results = null; 248 try { 249 ContentResolver cr = getContentResolverForUser(getChangingUserId()); 250 results = cr.applyBatch(TvContract.AUTHORITY, operations); 251 } catch (RemoteException | OperationApplicationException e) { 252 Slog.e(TAG, "error in applyBatch", e); 253 } 254 255 if (DEBUG) { 256 Slog.d(TAG, "onPackageRemoved(packageName=" + packageName + ", uid=" + uid 257 + ")"); 258 Slog.d(TAG, "results=" + results); 259 } 260 } 261 }; 262 monitor.register(mContext, null, UserHandle.ALL, true); 263 264 IntentFilter intentFilter = new IntentFilter(); 265 intentFilter.addAction(Intent.ACTION_USER_SWITCHED); 266 intentFilter.addAction(Intent.ACTION_USER_REMOVED); 267 mContext.registerReceiverAsUser(new BroadcastReceiver() { 268 @Override 269 public void onReceive(Context context, Intent intent) { 270 String action = intent.getAction(); 271 if (Intent.ACTION_USER_SWITCHED.equals(action)) { 272 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0)); 273 } else if (Intent.ACTION_USER_REMOVED.equals(action)) { 274 removeUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0)); 275 } 276 } 277 }, UserHandle.ALL, intentFilter, null, null); 278 } 279 280 private static boolean hasHardwarePermission(PackageManager pm, ComponentName component) { 281 return pm.checkPermission(android.Manifest.permission.TV_INPUT_HARDWARE, 282 component.getPackageName()) == PackageManager.PERMISSION_GRANTED; 283 } 284 285 private void buildTvInputListLocked(int userId, String[] updatedPackages) { 286 UserState userState = getOrCreateUserStateLocked(userId); 287 userState.packageSet.clear(); 288 289 if (DEBUG) Slog.d(TAG, "buildTvInputList"); 290 PackageManager pm = mContext.getPackageManager(); 291 List<ResolveInfo> services = pm.queryIntentServicesAsUser( 292 new Intent(TvInputService.SERVICE_INTERFACE), 293 PackageManager.GET_SERVICES | PackageManager.GET_META_DATA, 294 userId); 295 List<TvInputInfo> inputList = new ArrayList<>(); 296 for (ResolveInfo ri : services) { 297 ServiceInfo si = ri.serviceInfo; 298 if (!android.Manifest.permission.BIND_TV_INPUT.equals(si.permission)) { 299 Slog.w(TAG, "Skipping TV input " + si.name + ": it does not require the permission " 300 + android.Manifest.permission.BIND_TV_INPUT); 301 continue; 302 } 303 304 ComponentName component = new ComponentName(si.packageName, si.name); 305 if (hasHardwarePermission(pm, component)) { 306 ServiceState serviceState = userState.serviceStateMap.get(component); 307 if (serviceState == null) { 308 // New hardware input found. Create a new ServiceState and connect to the 309 // service to populate the hardware list. 310 serviceState = new ServiceState(component, userId); 311 userState.serviceStateMap.put(component, serviceState); 312 updateServiceConnectionLocked(component, userId); 313 } else { 314 inputList.addAll(serviceState.hardwareInputList); 315 } 316 } else { 317 try { 318 TvInputInfo info = new TvInputInfo.Builder(mContext, ri).build(); 319 inputList.add(info); 320 } catch (XmlPullParserException | IOException e) { 321 Slog.e(TAG, "failed to load TV input " + si.name, e); 322 continue; 323 } 324 } 325 userState.packageSet.add(si.packageName); 326 } 327 328 Map<String, TvInputState> inputMap = new HashMap<>(); 329 for (TvInputInfo info : inputList) { 330 if (DEBUG) { 331 Slog.d(TAG, "add " + info.getId()); 332 } 333 TvInputState inputState = userState.inputMap.get(info.getId()); 334 if (inputState == null) { 335 inputState = new TvInputState(); 336 inputState.info = info; 337 } 338 inputMap.put(info.getId(), inputState); 339 } 340 341 for (String inputId : inputMap.keySet()) { 342 if (!userState.inputMap.containsKey(inputId)) { 343 notifyInputAddedLocked(userState, inputId); 344 } else if (updatedPackages != null) { 345 // Notify the package updates 346 ComponentName component = inputMap.get(inputId).info.getComponent(); 347 for (String updatedPackage : updatedPackages) { 348 if (component.getPackageName().equals(updatedPackage)) { 349 updateServiceConnectionLocked(component, userId); 350 notifyInputUpdatedLocked(userState, inputId); 351 break; 352 } 353 } 354 } 355 } 356 357 for (String inputId : userState.inputMap.keySet()) { 358 if (!inputMap.containsKey(inputId)) { 359 TvInputInfo info = userState.inputMap.get(inputId).info; 360 ServiceState serviceState = userState.serviceStateMap.get(info.getComponent()); 361 if (serviceState != null) { 362 abortPendingCreateSessionRequestsLocked(serviceState, inputId, userId); 363 } 364 notifyInputRemovedLocked(userState, inputId); 365 } 366 } 367 368 userState.inputMap.clear(); 369 userState.inputMap = inputMap; 370 } 371 372 private void buildTvContentRatingSystemListLocked(int userId) { 373 UserState userState = getOrCreateUserStateLocked(userId); 374 userState.contentRatingSystemList.clear(); 375 376 final PackageManager pm = mContext.getPackageManager(); 377 Intent intent = new Intent(TvInputManager.ACTION_QUERY_CONTENT_RATING_SYSTEMS); 378 for (ResolveInfo resolveInfo : 379 pm.queryBroadcastReceivers(intent, PackageManager.GET_META_DATA)) { 380 ActivityInfo receiver = resolveInfo.activityInfo; 381 Bundle metaData = receiver.metaData; 382 if (metaData == null) { 383 continue; 384 } 385 386 int xmlResId = metaData.getInt(TvInputManager.META_DATA_CONTENT_RATING_SYSTEMS); 387 if (xmlResId == 0) { 388 Slog.w(TAG, "Missing meta-data '" 389 + TvInputManager.META_DATA_CONTENT_RATING_SYSTEMS + "' on receiver " 390 + receiver.packageName + "/" + receiver.name); 391 continue; 392 } 393 userState.contentRatingSystemList.add( 394 TvContentRatingSystemInfo.createTvContentRatingSystemInfo(xmlResId, 395 receiver.applicationInfo)); 396 } 397 } 398 399 private void switchUser(int userId) { 400 synchronized (mLock) { 401 if (mCurrentUserId == userId) { 402 return; 403 } 404 clearSessionAndServiceStatesLocked(mUserStates.get(mCurrentUserId)); 405 406 mCurrentUserId = userId; 407 getOrCreateUserStateLocked(userId); 408 buildTvInputListLocked(userId, null); 409 buildTvContentRatingSystemListLocked(userId); 410 mWatchLogHandler.obtainMessage(WatchLogHandler.MSG_SWITCH_CONTENT_RESOLVER, 411 getContentResolverForUser(userId)).sendToTarget(); 412 } 413 } 414 415 private void removeUser(int userId) { 416 synchronized (mLock) { 417 UserState userState = mUserStates.get(userId); 418 if (userState == null) { 419 return; 420 } 421 clearSessionAndServiceStatesLocked(userState); 422 423 // Clear everything else. 424 userState.inputMap.clear(); 425 userState.packageSet.clear(); 426 userState.contentRatingSystemList.clear(); 427 userState.clientStateMap.clear(); 428 userState.callbackSet.clear(); 429 userState.mainSessionToken = null; 430 431 mUserStates.remove(userId); 432 } 433 } 434 435 private void clearSessionAndServiceStatesLocked(UserState userState) { 436 // Release created sessions. 437 for (SessionState state : userState.sessionStateMap.values()) { 438 if (state.session != null) { 439 try { 440 state.session.release(); 441 } catch (RemoteException e) { 442 Slog.e(TAG, "error in release", e); 443 } 444 } 445 } 446 userState.sessionStateMap.clear(); 447 448 // Unregister all callbacks and unbind all services. 449 for (ServiceState serviceState : userState.serviceStateMap.values()) { 450 if (serviceState.service != null) { 451 if (serviceState.callback != null) { 452 try { 453 serviceState.service.unregisterCallback(serviceState.callback); 454 } catch (RemoteException e) { 455 Slog.e(TAG, "error in unregisterCallback", e); 456 } 457 } 458 mContext.unbindService(serviceState.connection); 459 } 460 } 461 userState.serviceStateMap.clear(); 462 } 463 464 private ContentResolver getContentResolverForUser(int userId) { 465 UserHandle user = new UserHandle(userId); 466 Context context; 467 try { 468 context = mContext.createPackageContextAsUser("android", 0, user); 469 } catch (NameNotFoundException e) { 470 Slog.e(TAG, "failed to create package context as user " + user); 471 context = mContext; 472 } 473 return context.getContentResolver(); 474 } 475 476 private UserState getOrCreateUserStateLocked(int userId) { 477 UserState userState = mUserStates.get(userId); 478 if (userState == null) { 479 userState = new UserState(mContext, userId); 480 mUserStates.put(userId, userState); 481 } 482 return userState; 483 } 484 485 private ServiceState getServiceStateLocked(ComponentName component, int userId) { 486 UserState userState = getOrCreateUserStateLocked(userId); 487 ServiceState serviceState = userState.serviceStateMap.get(component); 488 if (serviceState == null) { 489 throw new IllegalStateException("Service state not found for " + component + " (userId=" 490 + userId + ")"); 491 } 492 return serviceState; 493 } 494 495 private SessionState getSessionStateLocked(IBinder sessionToken, int callingUid, int userId) { 496 UserState userState = getOrCreateUserStateLocked(userId); 497 SessionState sessionState = userState.sessionStateMap.get(sessionToken); 498 if (sessionState == null) { 499 throw new SessionNotFoundException("Session state not found for token " + sessionToken); 500 } 501 // Only the application that requested this session or the system can access it. 502 if (callingUid != Process.SYSTEM_UID && callingUid != sessionState.callingUid) { 503 throw new SecurityException("Illegal access to the session with token " + sessionToken 504 + " from uid " + callingUid); 505 } 506 return sessionState; 507 } 508 509 private ITvInputSession getSessionLocked(IBinder sessionToken, int callingUid, int userId) { 510 return getSessionLocked(getSessionStateLocked(sessionToken, callingUid, userId)); 511 } 512 513 private ITvInputSession getSessionLocked(SessionState sessionState) { 514 ITvInputSession session = sessionState.session; 515 if (session == null) { 516 throw new IllegalStateException("Session not yet created for token " 517 + sessionState.sessionToken); 518 } 519 return session; 520 } 521 522 private int resolveCallingUserId(int callingPid, int callingUid, int requestedUserId, 523 String methodName) { 524 return ActivityManager.handleIncomingUser(callingPid, callingUid, requestedUserId, false, 525 false, methodName, null); 526 } 527 528 private static boolean shouldMaintainConnection(ServiceState serviceState) { 529 return !serviceState.sessionTokens.isEmpty() || serviceState.isHardware; 530 // TODO: Find a way to maintain connection to hardware TV input service only when necessary. 531 } 532 533 private void updateServiceConnectionLocked(ComponentName component, int userId) { 534 UserState userState = getOrCreateUserStateLocked(userId); 535 ServiceState serviceState = userState.serviceStateMap.get(component); 536 if (serviceState == null) { 537 return; 538 } 539 if (serviceState.reconnecting) { 540 if (!serviceState.sessionTokens.isEmpty()) { 541 // wait until all the sessions are removed. 542 return; 543 } 544 serviceState.reconnecting = false; 545 } 546 boolean maintainConnection = shouldMaintainConnection(serviceState); 547 if (serviceState.service == null && maintainConnection && userId == mCurrentUserId) { 548 // This means that the service is not yet connected but its state indicates that we 549 // have pending requests. Then, connect the service. 550 if (serviceState.bound) { 551 // We have already bound to the service so we don't try to bind again until after we 552 // unbind later on. 553 return; 554 } 555 if (DEBUG) { 556 Slog.d(TAG, "bindServiceAsUser(service=" + component + ", userId=" + userId + ")"); 557 } 558 559 Intent i = new Intent(TvInputService.SERVICE_INTERFACE).setComponent(component); 560 serviceState.bound = mContext.bindServiceAsUser( 561 i, serviceState.connection, 562 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE, 563 new UserHandle(userId)); 564 } else if (serviceState.service != null && !maintainConnection) { 565 // This means that the service is already connected but its state indicates that we have 566 // nothing to do with it. Then, disconnect the service. 567 if (DEBUG) { 568 Slog.d(TAG, "unbindService(service=" + component + ")"); 569 } 570 mContext.unbindService(serviceState.connection); 571 userState.serviceStateMap.remove(component); 572 } 573 } 574 575 private void abortPendingCreateSessionRequestsLocked(ServiceState serviceState, 576 String inputId, int userId) { 577 // Let clients know the create session requests are failed. 578 UserState userState = getOrCreateUserStateLocked(userId); 579 List<SessionState> sessionsToAbort = new ArrayList<>(); 580 for (IBinder sessionToken : serviceState.sessionTokens) { 581 SessionState sessionState = userState.sessionStateMap.get(sessionToken); 582 if (sessionState.session == null && (inputId == null 583 || sessionState.inputId.equals(inputId))) { 584 sessionsToAbort.add(sessionState); 585 } 586 } 587 for (SessionState sessionState : sessionsToAbort) { 588 removeSessionStateLocked(sessionState.sessionToken, sessionState.userId); 589 sendSessionTokenToClientLocked(sessionState.client, 590 sessionState.inputId, null, null, sessionState.seq); 591 } 592 updateServiceConnectionLocked(serviceState.component, userId); 593 } 594 595 private void createSessionInternalLocked(ITvInputService service, IBinder sessionToken, 596 int userId) { 597 UserState userState = getOrCreateUserStateLocked(userId); 598 SessionState sessionState = userState.sessionStateMap.get(sessionToken); 599 if (DEBUG) { 600 Slog.d(TAG, "createSessionInternalLocked(inputId=" + sessionState.inputId + ")"); 601 } 602 InputChannel[] channels = InputChannel.openInputChannelPair(sessionToken.toString()); 603 604 // Set up a callback to send the session token. 605 ITvInputSessionCallback callback = new SessionCallback(sessionState, channels); 606 607 // Create a session. When failed, send a null token immediately. 608 try { 609 if (sessionState.isRecordingSession) { 610 service.createRecordingSession(callback, sessionState.inputId); 611 } else { 612 service.createSession(channels[1], callback, sessionState.inputId); 613 } 614 } catch (RemoteException e) { 615 Slog.e(TAG, "error in createSession", e); 616 removeSessionStateLocked(sessionToken, userId); 617 sendSessionTokenToClientLocked(sessionState.client, sessionState.inputId, null, 618 null, sessionState.seq); 619 } 620 channels[1].dispose(); 621 } 622 623 private void sendSessionTokenToClientLocked(ITvInputClient client, String inputId, 624 IBinder sessionToken, InputChannel channel, int seq) { 625 try { 626 client.onSessionCreated(inputId, sessionToken, channel, seq); 627 } catch (RemoteException e) { 628 Slog.e(TAG, "error in onSessionCreated", e); 629 } 630 } 631 632 private void releaseSessionLocked(IBinder sessionToken, int callingUid, int userId) { 633 SessionState sessionState = null; 634 try { 635 sessionState = getSessionStateLocked(sessionToken, callingUid, userId); 636 if (sessionState.session != null) { 637 UserState userState = getOrCreateUserStateLocked(userId); 638 if (sessionToken == userState.mainSessionToken) { 639 setMainLocked(sessionToken, false, callingUid, userId); 640 } 641 sessionState.session.release(); 642 } 643 } catch (RemoteException | SessionNotFoundException e) { 644 Slog.e(TAG, "error in releaseSession", e); 645 } finally { 646 if (sessionState != null) { 647 sessionState.session = null; 648 } 649 } 650 removeSessionStateLocked(sessionToken, userId); 651 } 652 653 private void removeSessionStateLocked(IBinder sessionToken, int userId) { 654 UserState userState = getOrCreateUserStateLocked(userId); 655 if (sessionToken == userState.mainSessionToken) { 656 if (DEBUG) { 657 Slog.d(TAG, "mainSessionToken=null"); 658 } 659 userState.mainSessionToken = null; 660 } 661 662 // Remove the session state from the global session state map of the current user. 663 SessionState sessionState = userState.sessionStateMap.remove(sessionToken); 664 665 if (sessionState == null) { 666 return; 667 } 668 669 // Also remove the session token from the session token list of the current client and 670 // service. 671 ClientState clientState = userState.clientStateMap.get(sessionState.client.asBinder()); 672 if (clientState != null) { 673 clientState.sessionTokens.remove(sessionToken); 674 if (clientState.isEmpty()) { 675 userState.clientStateMap.remove(sessionState.client.asBinder()); 676 } 677 } 678 679 ServiceState serviceState = userState.serviceStateMap.get(sessionState.componentName); 680 if (serviceState != null) { 681 serviceState.sessionTokens.remove(sessionToken); 682 } 683 updateServiceConnectionLocked(sessionState.componentName, userId); 684 685 // Log the end of watch. 686 SomeArgs args = SomeArgs.obtain(); 687 args.arg1 = sessionToken; 688 args.arg2 = System.currentTimeMillis(); 689 mWatchLogHandler.obtainMessage(WatchLogHandler.MSG_LOG_WATCH_END, args).sendToTarget(); 690 } 691 692 private void setMainLocked(IBinder sessionToken, boolean isMain, int callingUid, int userId) { 693 try { 694 SessionState sessionState = getSessionStateLocked(sessionToken, callingUid, userId); 695 if (sessionState.hardwareSessionToken != null) { 696 sessionState = getSessionStateLocked(sessionState.hardwareSessionToken, 697 Process.SYSTEM_UID, userId); 698 } 699 ServiceState serviceState = getServiceStateLocked(sessionState.componentName, userId); 700 if (!serviceState.isHardware) { 701 return; 702 } 703 ITvInputSession session = getSessionLocked(sessionState); 704 session.setMain(isMain); 705 } catch (RemoteException | SessionNotFoundException e) { 706 Slog.e(TAG, "error in setMain", e); 707 } 708 } 709 710 private void notifyInputAddedLocked(UserState userState, String inputId) { 711 if (DEBUG) { 712 Slog.d(TAG, "notifyInputAddedLocked(inputId=" + inputId + ")"); 713 } 714 for (ITvInputManagerCallback callback : userState.callbackSet) { 715 try { 716 callback.onInputAdded(inputId); 717 } catch (RemoteException e) { 718 Slog.e(TAG, "failed to report added input to callback", e); 719 } 720 } 721 } 722 723 private void notifyInputRemovedLocked(UserState userState, String inputId) { 724 if (DEBUG) { 725 Slog.d(TAG, "notifyInputRemovedLocked(inputId=" + inputId + ")"); 726 } 727 for (ITvInputManagerCallback callback : userState.callbackSet) { 728 try { 729 callback.onInputRemoved(inputId); 730 } catch (RemoteException e) { 731 Slog.e(TAG, "failed to report removed input to callback", e); 732 } 733 } 734 } 735 736 private void notifyInputUpdatedLocked(UserState userState, String inputId) { 737 if (DEBUG) { 738 Slog.d(TAG, "notifyInputUpdatedLocked(inputId=" + inputId + ")"); 739 } 740 for (ITvInputManagerCallback callback : userState.callbackSet) { 741 try { 742 callback.onInputUpdated(inputId); 743 } catch (RemoteException e) { 744 Slog.e(TAG, "failed to report updated input to callback", e); 745 } 746 } 747 } 748 749 private void notifyInputStateChangedLocked(UserState userState, String inputId, 750 int state, ITvInputManagerCallback targetCallback) { 751 if (DEBUG) { 752 Slog.d(TAG, "notifyInputStateChangedLocked(inputId=" + inputId 753 + ", state=" + state + ")"); 754 } 755 if (targetCallback == null) { 756 for (ITvInputManagerCallback callback : userState.callbackSet) { 757 try { 758 callback.onInputStateChanged(inputId, state); 759 } catch (RemoteException e) { 760 Slog.e(TAG, "failed to report state change to callback", e); 761 } 762 } 763 } else { 764 try { 765 targetCallback.onInputStateChanged(inputId, state); 766 } catch (RemoteException e) { 767 Slog.e(TAG, "failed to report state change to callback", e); 768 } 769 } 770 } 771 772 private void updateTvInputInfoLocked(UserState userState, TvInputInfo inputInfo) { 773 if (DEBUG) { 774 Slog.d(TAG, "updateTvInputInfoLocked(inputInfo=" + inputInfo + ")"); 775 } 776 String inputId = inputInfo.getId(); 777 TvInputState inputState = userState.inputMap.get(inputId); 778 if (inputState == null) { 779 Slog.e(TAG, "failed to set input info - unknown input id " + inputId); 780 return; 781 } 782 inputState.info = inputInfo; 783 784 for (ITvInputManagerCallback callback : userState.callbackSet) { 785 try { 786 callback.onTvInputInfoUpdated(inputInfo); 787 } catch (RemoteException e) { 788 Slog.e(TAG, "failed to report updated input info to callback", e); 789 } 790 } 791 } 792 793 private void setStateLocked(String inputId, int state, int userId) { 794 UserState userState = getOrCreateUserStateLocked(userId); 795 TvInputState inputState = userState.inputMap.get(inputId); 796 ServiceState serviceState = userState.serviceStateMap.get(inputState.info.getComponent()); 797 int oldState = inputState.state; 798 inputState.state = state; 799 if (serviceState != null && serviceState.service == null 800 && shouldMaintainConnection(serviceState)) { 801 // We don't notify state change while reconnecting. It should remain disconnected. 802 return; 803 } 804 if (oldState != state) { 805 notifyInputStateChangedLocked(userState, inputId, state, null); 806 } 807 } 808 809 private final class BinderService extends ITvInputManager.Stub { 810 @Override 811 public List<TvInputInfo> getTvInputList(int userId) { 812 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), 813 Binder.getCallingUid(), userId, "getTvInputList"); 814 final long identity = Binder.clearCallingIdentity(); 815 try { 816 synchronized (mLock) { 817 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 818 List<TvInputInfo> inputList = new ArrayList<>(); 819 for (TvInputState state : userState.inputMap.values()) { 820 inputList.add(state.info); 821 } 822 return inputList; 823 } 824 } finally { 825 Binder.restoreCallingIdentity(identity); 826 } 827 } 828 829 @Override 830 public TvInputInfo getTvInputInfo(String inputId, int userId) { 831 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), 832 Binder.getCallingUid(), userId, "getTvInputInfo"); 833 final long identity = Binder.clearCallingIdentity(); 834 try { 835 synchronized (mLock) { 836 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 837 TvInputState state = userState.inputMap.get(inputId); 838 return state == null ? null : state.info; 839 } 840 } finally { 841 Binder.restoreCallingIdentity(identity); 842 } 843 } 844 845 public void updateTvInputInfo(TvInputInfo inputInfo, int userId) { 846 String inputInfoPackageName = inputInfo.getServiceInfo().packageName; 847 String callingPackageName = getCallingPackageName(); 848 if (!TextUtils.equals(inputInfoPackageName, callingPackageName)) { 849 throw new IllegalArgumentException("calling package " + callingPackageName 850 + " is not allowed to change TvInputInfo for " + inputInfoPackageName); 851 } 852 853 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), 854 Binder.getCallingUid(), userId, "updateTvInputInfo"); 855 final long identity = Binder.clearCallingIdentity(); 856 try { 857 synchronized (mLock) { 858 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 859 updateTvInputInfoLocked(userState, inputInfo); 860 } 861 } finally { 862 Binder.restoreCallingIdentity(identity); 863 } 864 } 865 866 private String getCallingPackageName() { 867 final String[] packages = mContext.getPackageManager().getPackagesForUid( 868 Binder.getCallingUid()); 869 if (packages != null && packages.length > 0) { 870 return packages[0]; 871 } 872 return "unknown"; 873 } 874 875 @Override 876 public int getTvInputState(String inputId, int userId) { 877 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), 878 Binder.getCallingUid(), userId, "getTvInputState"); 879 final long identity = Binder.clearCallingIdentity(); 880 try { 881 synchronized (mLock) { 882 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 883 TvInputState state = userState.inputMap.get(inputId); 884 return state == null ? INPUT_STATE_CONNECTED : state.state; 885 } 886 } finally { 887 Binder.restoreCallingIdentity(identity); 888 } 889 } 890 891 @Override 892 public List<TvContentRatingSystemInfo> getTvContentRatingSystemList(int userId) { 893 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), 894 Binder.getCallingUid(), userId, "getTvContentRatingSystemList"); 895 final long identity = Binder.clearCallingIdentity(); 896 try { 897 synchronized (mLock) { 898 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 899 return userState.contentRatingSystemList; 900 } 901 } finally { 902 Binder.restoreCallingIdentity(identity); 903 } 904 } 905 906 @Override 907 public void registerCallback(final ITvInputManagerCallback callback, int userId) { 908 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), 909 Binder.getCallingUid(), userId, "registerCallback"); 910 final long identity = Binder.clearCallingIdentity(); 911 try { 912 synchronized (mLock) { 913 final UserState userState = getOrCreateUserStateLocked(resolvedUserId); 914 userState.callbackSet.add(callback); 915 try { 916 callback.asBinder().linkToDeath(new IBinder.DeathRecipient() { 917 @Override 918 public void binderDied() { 919 synchronized (mLock) { 920 if (userState.callbackSet != null) { 921 userState.callbackSet.remove(callback); 922 } 923 } 924 } 925 }, 0); 926 } catch (RemoteException e) { 927 Slog.e(TAG, "client process has already died", e); 928 } 929 } 930 } finally { 931 Binder.restoreCallingIdentity(identity); 932 } 933 } 934 935 @Override 936 public void unregisterCallback(ITvInputManagerCallback callback, int userId) { 937 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), 938 Binder.getCallingUid(), userId, "unregisterCallback"); 939 final long identity = Binder.clearCallingIdentity(); 940 try { 941 synchronized (mLock) { 942 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 943 userState.callbackSet.remove(callback); 944 } 945 } finally { 946 Binder.restoreCallingIdentity(identity); 947 } 948 } 949 950 @Override 951 public boolean isParentalControlsEnabled(int userId) { 952 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), 953 Binder.getCallingUid(), userId, "isParentalControlsEnabled"); 954 final long identity = Binder.clearCallingIdentity(); 955 try { 956 synchronized (mLock) { 957 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 958 return userState.persistentDataStore.isParentalControlsEnabled(); 959 } 960 } finally { 961 Binder.restoreCallingIdentity(identity); 962 } 963 } 964 965 @Override 966 public void setParentalControlsEnabled(boolean enabled, int userId) { 967 ensureParentalControlsPermission(); 968 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), 969 Binder.getCallingUid(), userId, "setParentalControlsEnabled"); 970 final long identity = Binder.clearCallingIdentity(); 971 try { 972 synchronized (mLock) { 973 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 974 userState.persistentDataStore.setParentalControlsEnabled(enabled); 975 } 976 } finally { 977 Binder.restoreCallingIdentity(identity); 978 } 979 } 980 981 @Override 982 public boolean isRatingBlocked(String rating, int userId) { 983 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), 984 Binder.getCallingUid(), userId, "isRatingBlocked"); 985 final long identity = Binder.clearCallingIdentity(); 986 try { 987 synchronized (mLock) { 988 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 989 return userState.persistentDataStore.isRatingBlocked( 990 TvContentRating.unflattenFromString(rating)); 991 } 992 } finally { 993 Binder.restoreCallingIdentity(identity); 994 } 995 } 996 997 @Override 998 public List<String> getBlockedRatings(int userId) { 999 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), 1000 Binder.getCallingUid(), userId, "getBlockedRatings"); 1001 final long identity = Binder.clearCallingIdentity(); 1002 try { 1003 synchronized (mLock) { 1004 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 1005 List<String> ratings = new ArrayList<>(); 1006 for (TvContentRating rating 1007 : userState.persistentDataStore.getBlockedRatings()) { 1008 ratings.add(rating.flattenToString()); 1009 } 1010 return ratings; 1011 } 1012 } finally { 1013 Binder.restoreCallingIdentity(identity); 1014 } 1015 } 1016 1017 @Override 1018 public void addBlockedRating(String rating, int userId) { 1019 ensureParentalControlsPermission(); 1020 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), 1021 Binder.getCallingUid(), userId, "addBlockedRating"); 1022 final long identity = Binder.clearCallingIdentity(); 1023 try { 1024 synchronized (mLock) { 1025 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 1026 userState.persistentDataStore.addBlockedRating( 1027 TvContentRating.unflattenFromString(rating)); 1028 } 1029 } finally { 1030 Binder.restoreCallingIdentity(identity); 1031 } 1032 } 1033 1034 @Override 1035 public void removeBlockedRating(String rating, int userId) { 1036 ensureParentalControlsPermission(); 1037 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), 1038 Binder.getCallingUid(), userId, "removeBlockedRating"); 1039 final long identity = Binder.clearCallingIdentity(); 1040 try { 1041 synchronized (mLock) { 1042 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 1043 userState.persistentDataStore.removeBlockedRating( 1044 TvContentRating.unflattenFromString(rating)); 1045 } 1046 } finally { 1047 Binder.restoreCallingIdentity(identity); 1048 } 1049 } 1050 1051 private void ensureParentalControlsPermission() { 1052 if (mContext.checkCallingPermission( 1053 android.Manifest.permission.MODIFY_PARENTAL_CONTROLS) 1054 != PackageManager.PERMISSION_GRANTED) { 1055 throw new SecurityException( 1056 "The caller does not have parental controls permission"); 1057 } 1058 } 1059 1060 @Override 1061 public void createSession(final ITvInputClient client, final String inputId, 1062 boolean isRecordingSession, int seq, int userId) { 1063 final int callingUid = Binder.getCallingUid(); 1064 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1065 userId, "createSession"); 1066 final long identity = Binder.clearCallingIdentity(); 1067 try { 1068 synchronized (mLock) { 1069 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 1070 TvInputState inputState = userState.inputMap.get(inputId); 1071 if (inputState == null) { 1072 Slog.w(TAG, "Failed to find input state for inputId=" + inputId); 1073 sendSessionTokenToClientLocked(client, inputId, null, null, seq); 1074 return; 1075 } 1076 TvInputInfo info = inputState.info; 1077 ServiceState serviceState = userState.serviceStateMap.get(info.getComponent()); 1078 if (serviceState == null) { 1079 serviceState = new ServiceState(info.getComponent(), resolvedUserId); 1080 userState.serviceStateMap.put(info.getComponent(), serviceState); 1081 } 1082 // Send a null token immediately while reconnecting. 1083 if (serviceState.reconnecting) { 1084 sendSessionTokenToClientLocked(client, inputId, null, null, seq); 1085 return; 1086 } 1087 1088 // Create a new session token and a session state. 1089 IBinder sessionToken = new Binder(); 1090 SessionState sessionState = new SessionState(sessionToken, info.getId(), 1091 info.getComponent(), isRecordingSession, client, seq, callingUid, 1092 resolvedUserId); 1093 1094 // Add them to the global session state map of the current user. 1095 userState.sessionStateMap.put(sessionToken, sessionState); 1096 1097 // Also, add them to the session state map of the current service. 1098 serviceState.sessionTokens.add(sessionToken); 1099 1100 if (serviceState.service != null) { 1101 createSessionInternalLocked(serviceState.service, sessionToken, 1102 resolvedUserId); 1103 } else { 1104 updateServiceConnectionLocked(info.getComponent(), resolvedUserId); 1105 } 1106 } 1107 } finally { 1108 Binder.restoreCallingIdentity(identity); 1109 } 1110 } 1111 1112 @Override 1113 public void releaseSession(IBinder sessionToken, int userId) { 1114 if (DEBUG) { 1115 Slog.d(TAG, "releaseSession(sessionToken=" + sessionToken + ")"); 1116 } 1117 final int callingUid = Binder.getCallingUid(); 1118 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1119 userId, "releaseSession"); 1120 final long identity = Binder.clearCallingIdentity(); 1121 try { 1122 synchronized (mLock) { 1123 releaseSessionLocked(sessionToken, callingUid, resolvedUserId); 1124 } 1125 } finally { 1126 Binder.restoreCallingIdentity(identity); 1127 } 1128 } 1129 1130 @Override 1131 public void setMainSession(IBinder sessionToken, int userId) { 1132 if (DEBUG) { 1133 Slog.d(TAG, "setMainSession(sessionToken=" + sessionToken + ")"); 1134 } 1135 final int callingUid = Binder.getCallingUid(); 1136 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1137 userId, "setMainSession"); 1138 final long identity = Binder.clearCallingIdentity(); 1139 try { 1140 synchronized (mLock) { 1141 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 1142 if (userState.mainSessionToken == sessionToken) { 1143 return; 1144 } 1145 if (DEBUG) { 1146 Slog.d(TAG, "mainSessionToken=" + sessionToken); 1147 } 1148 IBinder oldMainSessionToken = userState.mainSessionToken; 1149 userState.mainSessionToken = sessionToken; 1150 1151 // Inform the new main session first. 1152 // See {@link TvInputService.Session#onSetMain}. 1153 if (sessionToken != null) { 1154 setMainLocked(sessionToken, true, callingUid, userId); 1155 } 1156 if (oldMainSessionToken != null) { 1157 setMainLocked(oldMainSessionToken, false, Process.SYSTEM_UID, userId); 1158 } 1159 } 1160 } finally { 1161 Binder.restoreCallingIdentity(identity); 1162 } 1163 } 1164 1165 @Override 1166 public void setSurface(IBinder sessionToken, Surface surface, int userId) { 1167 final int callingUid = Binder.getCallingUid(); 1168 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1169 userId, "setSurface"); 1170 final long identity = Binder.clearCallingIdentity(); 1171 try { 1172 synchronized (mLock) { 1173 try { 1174 SessionState sessionState = getSessionStateLocked(sessionToken, callingUid, 1175 resolvedUserId); 1176 if (sessionState.hardwareSessionToken == null) { 1177 getSessionLocked(sessionState).setSurface(surface); 1178 } else { 1179 getSessionLocked(sessionState.hardwareSessionToken, 1180 Process.SYSTEM_UID, resolvedUserId).setSurface(surface); 1181 } 1182 } catch (RemoteException | SessionNotFoundException e) { 1183 Slog.e(TAG, "error in setSurface", e); 1184 } 1185 } 1186 } finally { 1187 if (surface != null) { 1188 // surface is not used in TvInputManagerService. 1189 surface.release(); 1190 } 1191 Binder.restoreCallingIdentity(identity); 1192 } 1193 } 1194 1195 @Override 1196 public void dispatchSurfaceChanged(IBinder sessionToken, int format, int width, 1197 int height, int userId) { 1198 final int callingUid = Binder.getCallingUid(); 1199 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1200 userId, "dispatchSurfaceChanged"); 1201 final long identity = Binder.clearCallingIdentity(); 1202 try { 1203 synchronized (mLock) { 1204 try { 1205 SessionState sessionState = getSessionStateLocked(sessionToken, callingUid, 1206 resolvedUserId); 1207 getSessionLocked(sessionState).dispatchSurfaceChanged(format, width, 1208 height); 1209 if (sessionState.hardwareSessionToken != null) { 1210 getSessionLocked(sessionState.hardwareSessionToken, Process.SYSTEM_UID, 1211 resolvedUserId).dispatchSurfaceChanged(format, width, height); 1212 } 1213 } catch (RemoteException | SessionNotFoundException e) { 1214 Slog.e(TAG, "error in dispatchSurfaceChanged", e); 1215 } 1216 } 1217 } finally { 1218 Binder.restoreCallingIdentity(identity); 1219 } 1220 } 1221 1222 @Override 1223 public void setVolume(IBinder sessionToken, float volume, int userId) { 1224 final float REMOTE_VOLUME_ON = 1.0f; 1225 final float REMOTE_VOLUME_OFF = 0f; 1226 final int callingUid = Binder.getCallingUid(); 1227 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1228 userId, "setVolume"); 1229 final long identity = Binder.clearCallingIdentity(); 1230 try { 1231 synchronized (mLock) { 1232 try { 1233 SessionState sessionState = getSessionStateLocked(sessionToken, callingUid, 1234 resolvedUserId); 1235 getSessionLocked(sessionState).setVolume(volume); 1236 if (sessionState.hardwareSessionToken != null) { 1237 // Here, we let the hardware session know only whether volume is on or 1238 // off to prevent that the volume is controlled in the both side. 1239 getSessionLocked(sessionState.hardwareSessionToken, 1240 Process.SYSTEM_UID, resolvedUserId).setVolume((volume > 0.0f) 1241 ? REMOTE_VOLUME_ON : REMOTE_VOLUME_OFF); 1242 } 1243 } catch (RemoteException | SessionNotFoundException e) { 1244 Slog.e(TAG, "error in setVolume", e); 1245 } 1246 } 1247 } finally { 1248 Binder.restoreCallingIdentity(identity); 1249 } 1250 } 1251 1252 @Override 1253 public void tune(IBinder sessionToken, final Uri channelUri, Bundle params, int userId) { 1254 final int callingUid = Binder.getCallingUid(); 1255 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1256 userId, "tune"); 1257 final long identity = Binder.clearCallingIdentity(); 1258 try { 1259 synchronized (mLock) { 1260 try { 1261 getSessionLocked(sessionToken, callingUid, resolvedUserId).tune( 1262 channelUri, params); 1263 if (TvContract.isChannelUriForPassthroughInput(channelUri)) { 1264 // Do not log the watch history for passthrough inputs. 1265 return; 1266 } 1267 1268 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 1269 SessionState sessionState = userState.sessionStateMap.get(sessionToken); 1270 if (sessionState.isRecordingSession) { 1271 return; 1272 } 1273 1274 // Log the start of watch. 1275 SomeArgs args = SomeArgs.obtain(); 1276 args.arg1 = sessionState.componentName.getPackageName(); 1277 args.arg2 = System.currentTimeMillis(); 1278 args.arg3 = ContentUris.parseId(channelUri); 1279 args.arg4 = params; 1280 args.arg5 = sessionToken; 1281 mWatchLogHandler.obtainMessage(WatchLogHandler.MSG_LOG_WATCH_START, args) 1282 .sendToTarget(); 1283 } catch (RemoteException | SessionNotFoundException e) { 1284 Slog.e(TAG, "error in tune", e); 1285 } 1286 } 1287 } finally { 1288 Binder.restoreCallingIdentity(identity); 1289 } 1290 } 1291 1292 @Override 1293 public void unblockContent( 1294 IBinder sessionToken, String unblockedRating, int userId) { 1295 ensureParentalControlsPermission(); 1296 final int callingUid = Binder.getCallingUid(); 1297 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1298 userId, "unblockContent"); 1299 final long identity = Binder.clearCallingIdentity(); 1300 try { 1301 synchronized (mLock) { 1302 try { 1303 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1304 .unblockContent(unblockedRating); 1305 } catch (RemoteException | SessionNotFoundException e) { 1306 Slog.e(TAG, "error in unblockContent", e); 1307 } 1308 } 1309 } finally { 1310 Binder.restoreCallingIdentity(identity); 1311 } 1312 } 1313 1314 @Override 1315 public void setCaptionEnabled(IBinder sessionToken, boolean enabled, int userId) { 1316 final int callingUid = Binder.getCallingUid(); 1317 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1318 userId, "setCaptionEnabled"); 1319 final long identity = Binder.clearCallingIdentity(); 1320 try { 1321 synchronized (mLock) { 1322 try { 1323 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1324 .setCaptionEnabled(enabled); 1325 } catch (RemoteException | SessionNotFoundException e) { 1326 Slog.e(TAG, "error in setCaptionEnabled", e); 1327 } 1328 } 1329 } finally { 1330 Binder.restoreCallingIdentity(identity); 1331 } 1332 } 1333 1334 @Override 1335 public void selectTrack(IBinder sessionToken, int type, String trackId, int userId) { 1336 final int callingUid = Binder.getCallingUid(); 1337 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1338 userId, "selectTrack"); 1339 final long identity = Binder.clearCallingIdentity(); 1340 try { 1341 synchronized (mLock) { 1342 try { 1343 getSessionLocked(sessionToken, callingUid, resolvedUserId).selectTrack( 1344 type, trackId); 1345 } catch (RemoteException | SessionNotFoundException e) { 1346 Slog.e(TAG, "error in selectTrack", e); 1347 } 1348 } 1349 } finally { 1350 Binder.restoreCallingIdentity(identity); 1351 } 1352 } 1353 1354 @Override 1355 public void sendAppPrivateCommand(IBinder sessionToken, String command, Bundle data, 1356 int userId) { 1357 final int callingUid = Binder.getCallingUid(); 1358 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1359 userId, "sendAppPrivateCommand"); 1360 final long identity = Binder.clearCallingIdentity(); 1361 try { 1362 synchronized (mLock) { 1363 try { 1364 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1365 .appPrivateCommand(command, data); 1366 } catch (RemoteException | SessionNotFoundException e) { 1367 Slog.e(TAG, "error in appPrivateCommand", e); 1368 } 1369 } 1370 } finally { 1371 Binder.restoreCallingIdentity(identity); 1372 } 1373 } 1374 1375 @Override 1376 public void createOverlayView(IBinder sessionToken, IBinder windowToken, Rect frame, 1377 int userId) { 1378 final int callingUid = Binder.getCallingUid(); 1379 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1380 userId, "createOverlayView"); 1381 final long identity = Binder.clearCallingIdentity(); 1382 try { 1383 synchronized (mLock) { 1384 try { 1385 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1386 .createOverlayView(windowToken, frame); 1387 } catch (RemoteException | SessionNotFoundException e) { 1388 Slog.e(TAG, "error in createOverlayView", e); 1389 } 1390 } 1391 } finally { 1392 Binder.restoreCallingIdentity(identity); 1393 } 1394 } 1395 1396 @Override 1397 public void relayoutOverlayView(IBinder sessionToken, Rect frame, int userId) { 1398 final int callingUid = Binder.getCallingUid(); 1399 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1400 userId, "relayoutOverlayView"); 1401 final long identity = Binder.clearCallingIdentity(); 1402 try { 1403 synchronized (mLock) { 1404 try { 1405 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1406 .relayoutOverlayView(frame); 1407 } catch (RemoteException | SessionNotFoundException e) { 1408 Slog.e(TAG, "error in relayoutOverlayView", e); 1409 } 1410 } 1411 } finally { 1412 Binder.restoreCallingIdentity(identity); 1413 } 1414 } 1415 1416 @Override 1417 public void removeOverlayView(IBinder sessionToken, int userId) { 1418 final int callingUid = Binder.getCallingUid(); 1419 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1420 userId, "removeOverlayView"); 1421 final long identity = Binder.clearCallingIdentity(); 1422 try { 1423 synchronized (mLock) { 1424 try { 1425 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1426 .removeOverlayView(); 1427 } catch (RemoteException | SessionNotFoundException e) { 1428 Slog.e(TAG, "error in removeOverlayView", e); 1429 } 1430 } 1431 } finally { 1432 Binder.restoreCallingIdentity(identity); 1433 } 1434 } 1435 1436 @Override 1437 public void timeShiftPlay(IBinder sessionToken, final Uri recordedProgramUri, int userId) { 1438 final int callingUid = Binder.getCallingUid(); 1439 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1440 userId, "timeShiftPlay"); 1441 final long identity = Binder.clearCallingIdentity(); 1442 try { 1443 synchronized (mLock) { 1444 try { 1445 getSessionLocked(sessionToken, callingUid, resolvedUserId).timeShiftPlay( 1446 recordedProgramUri); 1447 } catch (RemoteException | SessionNotFoundException e) { 1448 Slog.e(TAG, "error in timeShiftPlay", e); 1449 } 1450 } 1451 } finally { 1452 Binder.restoreCallingIdentity(identity); 1453 } 1454 } 1455 1456 @Override 1457 public void timeShiftPause(IBinder sessionToken, int userId) { 1458 final int callingUid = Binder.getCallingUid(); 1459 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1460 userId, "timeShiftPause"); 1461 final long identity = Binder.clearCallingIdentity(); 1462 try { 1463 synchronized (mLock) { 1464 try { 1465 getSessionLocked(sessionToken, callingUid, resolvedUserId).timeShiftPause(); 1466 } catch (RemoteException | SessionNotFoundException e) { 1467 Slog.e(TAG, "error in timeShiftPause", e); 1468 } 1469 } 1470 } finally { 1471 Binder.restoreCallingIdentity(identity); 1472 } 1473 } 1474 1475 @Override 1476 public void timeShiftResume(IBinder sessionToken, int userId) { 1477 final int callingUid = Binder.getCallingUid(); 1478 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1479 userId, "timeShiftResume"); 1480 final long identity = Binder.clearCallingIdentity(); 1481 try { 1482 synchronized (mLock) { 1483 try { 1484 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1485 .timeShiftResume(); 1486 } catch (RemoteException | SessionNotFoundException e) { 1487 Slog.e(TAG, "error in timeShiftResume", e); 1488 } 1489 } 1490 } finally { 1491 Binder.restoreCallingIdentity(identity); 1492 } 1493 } 1494 1495 @Override 1496 public void timeShiftSeekTo(IBinder sessionToken, long timeMs, int userId) { 1497 final int callingUid = Binder.getCallingUid(); 1498 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1499 userId, "timeShiftSeekTo"); 1500 final long identity = Binder.clearCallingIdentity(); 1501 try { 1502 synchronized (mLock) { 1503 try { 1504 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1505 .timeShiftSeekTo(timeMs); 1506 } catch (RemoteException | SessionNotFoundException e) { 1507 Slog.e(TAG, "error in timeShiftSeekTo", e); 1508 } 1509 } 1510 } finally { 1511 Binder.restoreCallingIdentity(identity); 1512 } 1513 } 1514 1515 @Override 1516 public void timeShiftSetPlaybackParams(IBinder sessionToken, PlaybackParams params, 1517 int userId) { 1518 final int callingUid = Binder.getCallingUid(); 1519 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1520 userId, "timeShiftSetPlaybackParams"); 1521 final long identity = Binder.clearCallingIdentity(); 1522 try { 1523 synchronized (mLock) { 1524 try { 1525 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1526 .timeShiftSetPlaybackParams(params); 1527 } catch (RemoteException | SessionNotFoundException e) { 1528 Slog.e(TAG, "error in timeShiftSetPlaybackParams", e); 1529 } 1530 } 1531 } finally { 1532 Binder.restoreCallingIdentity(identity); 1533 } 1534 } 1535 1536 @Override 1537 public void timeShiftEnablePositionTracking(IBinder sessionToken, boolean enable, 1538 int userId) { 1539 final int callingUid = Binder.getCallingUid(); 1540 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1541 userId, "timeShiftEnablePositionTracking"); 1542 final long identity = Binder.clearCallingIdentity(); 1543 try { 1544 synchronized (mLock) { 1545 try { 1546 getSessionLocked(sessionToken, callingUid, resolvedUserId) 1547 .timeShiftEnablePositionTracking(enable); 1548 } catch (RemoteException | SessionNotFoundException e) { 1549 Slog.e(TAG, "error in timeShiftEnablePositionTracking", e); 1550 } 1551 } 1552 } finally { 1553 Binder.restoreCallingIdentity(identity); 1554 } 1555 } 1556 1557 @Override 1558 public void startRecording(IBinder sessionToken, @Nullable Uri programUri, int userId) { 1559 final int callingUid = Binder.getCallingUid(); 1560 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1561 userId, "startRecording"); 1562 final long identity = Binder.clearCallingIdentity(); 1563 try { 1564 synchronized (mLock) { 1565 try { 1566 getSessionLocked(sessionToken, callingUid, resolvedUserId).startRecording( 1567 programUri); 1568 } catch (RemoteException | SessionNotFoundException e) { 1569 Slog.e(TAG, "error in startRecording", e); 1570 } 1571 } 1572 } finally { 1573 Binder.restoreCallingIdentity(identity); 1574 } 1575 } 1576 1577 @Override 1578 public void stopRecording(IBinder sessionToken, int userId) { 1579 final int callingUid = Binder.getCallingUid(); 1580 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1581 userId, "stopRecording"); 1582 final long identity = Binder.clearCallingIdentity(); 1583 try { 1584 synchronized (mLock) { 1585 try { 1586 getSessionLocked(sessionToken, callingUid, resolvedUserId).stopRecording(); 1587 } catch (RemoteException | SessionNotFoundException e) { 1588 Slog.e(TAG, "error in stopRecording", e); 1589 } 1590 } 1591 } finally { 1592 Binder.restoreCallingIdentity(identity); 1593 } 1594 } 1595 1596 @Override 1597 public List<TvInputHardwareInfo> getHardwareList() throws RemoteException { 1598 if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE) 1599 != PackageManager.PERMISSION_GRANTED) { 1600 return null; 1601 } 1602 1603 final long identity = Binder.clearCallingIdentity(); 1604 try { 1605 return mTvInputHardwareManager.getHardwareList(); 1606 } finally { 1607 Binder.restoreCallingIdentity(identity); 1608 } 1609 } 1610 1611 @Override 1612 public ITvInputHardware acquireTvInputHardware(int deviceId, 1613 ITvInputHardwareCallback callback, TvInputInfo info, int userId) 1614 throws RemoteException { 1615 if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE) 1616 != PackageManager.PERMISSION_GRANTED) { 1617 return null; 1618 } 1619 1620 final long identity = Binder.clearCallingIdentity(); 1621 final int callingUid = Binder.getCallingUid(); 1622 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1623 userId, "acquireTvInputHardware"); 1624 try { 1625 return mTvInputHardwareManager.acquireHardware( 1626 deviceId, callback, info, callingUid, resolvedUserId); 1627 } finally { 1628 Binder.restoreCallingIdentity(identity); 1629 } 1630 } 1631 1632 @Override 1633 public void releaseTvInputHardware(int deviceId, ITvInputHardware hardware, int userId) 1634 throws RemoteException { 1635 if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE) 1636 != PackageManager.PERMISSION_GRANTED) { 1637 return; 1638 } 1639 1640 final long identity = Binder.clearCallingIdentity(); 1641 final int callingUid = Binder.getCallingUid(); 1642 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1643 userId, "releaseTvInputHardware"); 1644 try { 1645 mTvInputHardwareManager.releaseHardware( 1646 deviceId, hardware, callingUid, resolvedUserId); 1647 } finally { 1648 Binder.restoreCallingIdentity(identity); 1649 } 1650 } 1651 1652 @Override 1653 public List<DvbDeviceInfo> getDvbDeviceList() throws RemoteException { 1654 if (mContext.checkCallingPermission(android.Manifest.permission.DVB_DEVICE) 1655 != PackageManager.PERMISSION_GRANTED) { 1656 throw new SecurityException("Requires DVB_DEVICE permission"); 1657 } 1658 1659 final long identity = Binder.clearCallingIdentity(); 1660 try { 1661 ArrayList<DvbDeviceInfo> deviceInfos = new ArrayList<>(); 1662 File devDirectory = new File("/dev"); 1663 for (String fileName : devDirectory.list()) { 1664 Matcher matcher = sFrontEndDevicePattern.matcher(fileName); 1665 if (matcher.find()) { 1666 int adapterId = Integer.parseInt(matcher.group(1)); 1667 int deviceId = Integer.parseInt(matcher.group(2)); 1668 deviceInfos.add(new DvbDeviceInfo(adapterId, deviceId)); 1669 } 1670 } 1671 return Collections.unmodifiableList(deviceInfos); 1672 } finally { 1673 Binder.restoreCallingIdentity(identity); 1674 } 1675 } 1676 1677 @Override 1678 public ParcelFileDescriptor openDvbDevice(DvbDeviceInfo info, int device) 1679 throws RemoteException { 1680 if (mContext.checkCallingPermission(android.Manifest.permission.DVB_DEVICE) 1681 != PackageManager.PERMISSION_GRANTED) { 1682 throw new SecurityException("Requires DVB_DEVICE permission"); 1683 } 1684 1685 final long identity = Binder.clearCallingIdentity(); 1686 try { 1687 String deviceFileName; 1688 switch (device) { 1689 case TvInputManager.DVB_DEVICE_DEMUX: 1690 deviceFileName = String.format("/dev/dvb%d.demux%d", info.getAdapterId(), 1691 info.getDeviceId()); 1692 break; 1693 case TvInputManager.DVB_DEVICE_DVR: 1694 deviceFileName = String.format("/dev/dvb%d.dvr%d", info.getAdapterId(), 1695 info.getDeviceId()); 1696 break; 1697 case TvInputManager.DVB_DEVICE_FRONTEND: 1698 deviceFileName = String.format("/dev/dvb%d.frontend%d", info.getAdapterId(), 1699 info.getDeviceId()); 1700 break; 1701 default: 1702 throw new IllegalArgumentException("Invalid DVB device: " + device); 1703 } 1704 try { 1705 // The DVB frontend device only needs to be opened in read/write mode, which 1706 // allows performing tuning operations. The DVB demux and DVR device are enough 1707 // to be opened in read only mode. 1708 return ParcelFileDescriptor.open(new File(deviceFileName), 1709 TvInputManager.DVB_DEVICE_FRONTEND == device 1710 ? ParcelFileDescriptor.MODE_READ_WRITE 1711 : ParcelFileDescriptor.MODE_READ_ONLY); 1712 } catch (FileNotFoundException e) { 1713 return null; 1714 } 1715 } finally { 1716 Binder.restoreCallingIdentity(identity); 1717 } 1718 } 1719 1720 @Override 1721 public List<TvStreamConfig> getAvailableTvStreamConfigList(String inputId, int userId) 1722 throws RemoteException { 1723 if (mContext.checkCallingPermission( 1724 android.Manifest.permission.CAPTURE_TV_INPUT) 1725 != PackageManager.PERMISSION_GRANTED) { 1726 throw new SecurityException("Requires CAPTURE_TV_INPUT permission"); 1727 } 1728 1729 final long identity = Binder.clearCallingIdentity(); 1730 final int callingUid = Binder.getCallingUid(); 1731 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1732 userId, "getAvailableTvStreamConfigList"); 1733 try { 1734 return mTvInputHardwareManager.getAvailableTvStreamConfigList( 1735 inputId, callingUid, resolvedUserId); 1736 } finally { 1737 Binder.restoreCallingIdentity(identity); 1738 } 1739 } 1740 1741 @Override 1742 public boolean captureFrame(String inputId, Surface surface, TvStreamConfig config, 1743 int userId) 1744 throws RemoteException { 1745 if (mContext.checkCallingPermission( 1746 android.Manifest.permission.CAPTURE_TV_INPUT) 1747 != PackageManager.PERMISSION_GRANTED) { 1748 throw new SecurityException("Requires CAPTURE_TV_INPUT permission"); 1749 } 1750 1751 final long identity = Binder.clearCallingIdentity(); 1752 final int callingUid = Binder.getCallingUid(); 1753 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1754 userId, "captureFrame"); 1755 try { 1756 String hardwareInputId = null; 1757 synchronized (mLock) { 1758 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 1759 if (userState.inputMap.get(inputId) == null) { 1760 Slog.e(TAG, "input not found for " + inputId); 1761 return false; 1762 } 1763 for (SessionState sessionState : userState.sessionStateMap.values()) { 1764 if (sessionState.inputId.equals(inputId) 1765 && sessionState.hardwareSessionToken != null) { 1766 hardwareInputId = userState.sessionStateMap.get( 1767 sessionState.hardwareSessionToken).inputId; 1768 break; 1769 } 1770 } 1771 } 1772 return mTvInputHardwareManager.captureFrame( 1773 (hardwareInputId != null) ? hardwareInputId : inputId, 1774 surface, config, callingUid, resolvedUserId); 1775 } finally { 1776 Binder.restoreCallingIdentity(identity); 1777 } 1778 } 1779 1780 @Override 1781 public boolean isSingleSessionActive(int userId) throws RemoteException { 1782 final long identity = Binder.clearCallingIdentity(); 1783 final int callingUid = Binder.getCallingUid(); 1784 final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, 1785 userId, "isSingleSessionActive"); 1786 try { 1787 synchronized (mLock) { 1788 UserState userState = getOrCreateUserStateLocked(resolvedUserId); 1789 if (userState.sessionStateMap.size() == 1) { 1790 return true; 1791 } else if (userState.sessionStateMap.size() == 2) { 1792 SessionState[] sessionStates = userState.sessionStateMap.values().toArray( 1793 new SessionState[2]); 1794 // Check if there is a wrapper input. 1795 if (sessionStates[0].hardwareSessionToken != null 1796 || sessionStates[1].hardwareSessionToken != null) { 1797 return true; 1798 } 1799 } 1800 return false; 1801 } 1802 } finally { 1803 Binder.restoreCallingIdentity(identity); 1804 } 1805 } 1806 1807 @Override 1808 @SuppressWarnings("resource") 1809 protected void dump(FileDescriptor fd, final PrintWriter writer, String[] args) { 1810 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " "); 1811 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 1812 != PackageManager.PERMISSION_GRANTED) { 1813 pw.println("Permission Denial: can't dump TvInputManager from pid=" 1814 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()); 1815 return; 1816 } 1817 1818 synchronized (mLock) { 1819 pw.println("User Ids (Current user: " + mCurrentUserId + "):"); 1820 pw.increaseIndent(); 1821 for (int i = 0; i < mUserStates.size(); i++) { 1822 int userId = mUserStates.keyAt(i); 1823 pw.println(Integer.valueOf(userId)); 1824 } 1825 pw.decreaseIndent(); 1826 1827 for (int i = 0; i < mUserStates.size(); i++) { 1828 int userId = mUserStates.keyAt(i); 1829 UserState userState = getOrCreateUserStateLocked(userId); 1830 pw.println("UserState (" + userId + "):"); 1831 pw.increaseIndent(); 1832 1833 pw.println("inputMap: inputId -> TvInputState"); 1834 pw.increaseIndent(); 1835 for (Map.Entry<String, TvInputState> entry: userState.inputMap.entrySet()) { 1836 pw.println(entry.getKey() + ": " + entry.getValue()); 1837 } 1838 pw.decreaseIndent(); 1839 1840 pw.println("packageSet:"); 1841 pw.increaseIndent(); 1842 for (String packageName : userState.packageSet) { 1843 pw.println(packageName); 1844 } 1845 pw.decreaseIndent(); 1846 1847 pw.println("clientStateMap: ITvInputClient -> ClientState"); 1848 pw.increaseIndent(); 1849 for (Map.Entry<IBinder, ClientState> entry : 1850 userState.clientStateMap.entrySet()) { 1851 ClientState client = entry.getValue(); 1852 pw.println(entry.getKey() + ": " + client); 1853 1854 pw.increaseIndent(); 1855 1856 pw.println("sessionTokens:"); 1857 pw.increaseIndent(); 1858 for (IBinder token : client.sessionTokens) { 1859 pw.println("" + token); 1860 } 1861 pw.decreaseIndent(); 1862 1863 pw.println("clientTokens: " + client.clientToken); 1864 pw.println("userId: " + client.userId); 1865 1866 pw.decreaseIndent(); 1867 } 1868 pw.decreaseIndent(); 1869 1870 pw.println("serviceStateMap: ComponentName -> ServiceState"); 1871 pw.increaseIndent(); 1872 for (Map.Entry<ComponentName, ServiceState> entry : 1873 userState.serviceStateMap.entrySet()) { 1874 ServiceState service = entry.getValue(); 1875 pw.println(entry.getKey() + ": " + service); 1876 1877 pw.increaseIndent(); 1878 1879 pw.println("sessionTokens:"); 1880 pw.increaseIndent(); 1881 for (IBinder token : service.sessionTokens) { 1882 pw.println("" + token); 1883 } 1884 pw.decreaseIndent(); 1885 1886 pw.println("service: " + service.service); 1887 pw.println("callback: " + service.callback); 1888 pw.println("bound: " + service.bound); 1889 pw.println("reconnecting: " + service.reconnecting); 1890 1891 pw.decreaseIndent(); 1892 } 1893 pw.decreaseIndent(); 1894 1895 pw.println("sessionStateMap: ITvInputSession -> SessionState"); 1896 pw.increaseIndent(); 1897 for (Map.Entry<IBinder, SessionState> entry : 1898 userState.sessionStateMap.entrySet()) { 1899 SessionState session = entry.getValue(); 1900 pw.println(entry.getKey() + ": " + session); 1901 1902 pw.increaseIndent(); 1903 pw.println("inputId: " + session.inputId); 1904 pw.println("client: " + session.client); 1905 pw.println("seq: " + session.seq); 1906 pw.println("callingUid: " + session.callingUid); 1907 pw.println("userId: " + session.userId); 1908 pw.println("sessionToken: " + session.sessionToken); 1909 pw.println("session: " + session.session); 1910 pw.println("logUri: " + session.logUri); 1911 pw.println("hardwareSessionToken: " + session.hardwareSessionToken); 1912 pw.decreaseIndent(); 1913 } 1914 pw.decreaseIndent(); 1915 1916 pw.println("callbackSet:"); 1917 pw.increaseIndent(); 1918 for (ITvInputManagerCallback callback : userState.callbackSet) { 1919 pw.println(callback.toString()); 1920 } 1921 pw.decreaseIndent(); 1922 1923 pw.println("mainSessionToken: " + userState.mainSessionToken); 1924 pw.decreaseIndent(); 1925 } 1926 } 1927 mTvInputHardwareManager.dump(fd, writer, args); 1928 } 1929 } 1930 1931 private static final class UserState { 1932 // A mapping from the TV input id to its TvInputState. 1933 private Map<String, TvInputState> inputMap = new HashMap<>(); 1934 1935 // A set of all TV input packages. 1936 private final Set<String> packageSet = new HashSet<>(); 1937 1938 // A list of all TV content rating systems defined. 1939 private final List<TvContentRatingSystemInfo> 1940 contentRatingSystemList = new ArrayList<>(); 1941 1942 // A mapping from the token of a client to its state. 1943 private final Map<IBinder, ClientState> clientStateMap = new HashMap<>(); 1944 1945 // A mapping from the name of a TV input service to its state. 1946 private final Map<ComponentName, ServiceState> serviceStateMap = new HashMap<>(); 1947 1948 // A mapping from the token of a TV input session to its state. 1949 private final Map<IBinder, SessionState> sessionStateMap = new HashMap<>(); 1950 1951 // A set of callbacks. 1952 private final Set<ITvInputManagerCallback> callbackSet = new HashSet<>(); 1953 1954 // The token of a "main" TV input session. 1955 private IBinder mainSessionToken = null; 1956 1957 // Persistent data store for all internal settings maintained by the TV input manager 1958 // service. 1959 private final PersistentDataStore persistentDataStore; 1960 1961 private UserState(Context context, int userId) { 1962 persistentDataStore = new PersistentDataStore(context, userId); 1963 } 1964 } 1965 1966 private final class ClientState implements IBinder.DeathRecipient { 1967 private final List<IBinder> sessionTokens = new ArrayList<>(); 1968 1969 private IBinder clientToken; 1970 private final int userId; 1971 1972 ClientState(IBinder clientToken, int userId) { 1973 this.clientToken = clientToken; 1974 this.userId = userId; 1975 } 1976 1977 public boolean isEmpty() { 1978 return sessionTokens.isEmpty(); 1979 } 1980 1981 @Override 1982 public void binderDied() { 1983 synchronized (mLock) { 1984 UserState userState = getOrCreateUserStateLocked(userId); 1985 // DO NOT remove the client state of clientStateMap in this method. It will be 1986 // removed in releaseSessionLocked(). 1987 ClientState clientState = userState.clientStateMap.get(clientToken); 1988 if (clientState != null) { 1989 while (clientState.sessionTokens.size() > 0) { 1990 releaseSessionLocked( 1991 clientState.sessionTokens.get(0), Process.SYSTEM_UID, userId); 1992 } 1993 } 1994 clientToken = null; 1995 } 1996 } 1997 } 1998 1999 private final class ServiceState { 2000 private final List<IBinder> sessionTokens = new ArrayList<>(); 2001 private final ServiceConnection connection; 2002 private final ComponentName component; 2003 private final boolean isHardware; 2004 private final List<TvInputInfo> hardwareInputList = new ArrayList<>(); 2005 2006 private ITvInputService service; 2007 private ServiceCallback callback; 2008 private boolean bound; 2009 private boolean reconnecting; 2010 2011 private ServiceState(ComponentName component, int userId) { 2012 this.component = component; 2013 this.connection = new InputServiceConnection(component, userId); 2014 this.isHardware = hasHardwarePermission(mContext.getPackageManager(), component); 2015 } 2016 } 2017 2018 private static final class TvInputState { 2019 // A TvInputInfo object which represents the TV input. 2020 private TvInputInfo info; 2021 2022 // The state of TV input. Connected by default. 2023 private int state = INPUT_STATE_CONNECTED; 2024 2025 @Override 2026 public String toString() { 2027 return "info: " + info + "; state: " + state; 2028 } 2029 } 2030 2031 private final class SessionState implements IBinder.DeathRecipient { 2032 private final String inputId; 2033 private final ComponentName componentName; 2034 private final boolean isRecordingSession; 2035 private final ITvInputClient client; 2036 private final int seq; 2037 private final int callingUid; 2038 private final int userId; 2039 private final IBinder sessionToken; 2040 private ITvInputSession session; 2041 private Uri logUri; 2042 // Not null if this session represents an external device connected to a hardware TV input. 2043 private IBinder hardwareSessionToken; 2044 2045 private SessionState(IBinder sessionToken, String inputId, ComponentName componentName, 2046 boolean isRecordingSession, ITvInputClient client, int seq, int callingUid, 2047 int userId) { 2048 this.sessionToken = sessionToken; 2049 this.inputId = inputId; 2050 this.componentName = componentName; 2051 this.isRecordingSession = isRecordingSession; 2052 this.client = client; 2053 this.seq = seq; 2054 this.callingUid = callingUid; 2055 this.userId = userId; 2056 } 2057 2058 @Override 2059 public void binderDied() { 2060 synchronized (mLock) { 2061 session = null; 2062 if (client != null) { 2063 try { 2064 client.onSessionReleased(seq); 2065 } catch(RemoteException e) { 2066 Slog.e(TAG, "error in onSessionReleased", e); 2067 } 2068 } 2069 // If there are any other sessions based on this session, they should be released. 2070 UserState userState = getOrCreateUserStateLocked(userId); 2071 for (SessionState sessionState : userState.sessionStateMap.values()) { 2072 if (sessionToken == sessionState.hardwareSessionToken) { 2073 releaseSessionLocked(sessionState.sessionToken, Process.SYSTEM_UID, 2074 userId); 2075 try { 2076 sessionState.client.onSessionReleased(sessionState.seq); 2077 } catch (RemoteException e) { 2078 Slog.e(TAG, "error in onSessionReleased", e); 2079 } 2080 } 2081 } 2082 removeSessionStateLocked(sessionToken, userId); 2083 } 2084 } 2085 } 2086 2087 private final class InputServiceConnection implements ServiceConnection { 2088 private final ComponentName mComponent; 2089 private final int mUserId; 2090 2091 private InputServiceConnection(ComponentName component, int userId) { 2092 mComponent = component; 2093 mUserId = userId; 2094 } 2095 2096 @Override 2097 public void onServiceConnected(ComponentName component, IBinder service) { 2098 if (DEBUG) { 2099 Slog.d(TAG, "onServiceConnected(component=" + component + ")"); 2100 } 2101 synchronized (mLock) { 2102 UserState userState = mUserStates.get(mUserId); 2103 if (userState == null) { 2104 // The user was removed while connecting. 2105 mContext.unbindService(this); 2106 return; 2107 } 2108 ServiceState serviceState = userState.serviceStateMap.get(mComponent); 2109 serviceState.service = ITvInputService.Stub.asInterface(service); 2110 2111 // Register a callback, if we need to. 2112 if (serviceState.isHardware && serviceState.callback == null) { 2113 serviceState.callback = new ServiceCallback(mComponent, mUserId); 2114 try { 2115 serviceState.service.registerCallback(serviceState.callback); 2116 } catch (RemoteException e) { 2117 Slog.e(TAG, "error in registerCallback", e); 2118 } 2119 } 2120 2121 // And create sessions, if any. 2122 for (IBinder sessionToken : serviceState.sessionTokens) { 2123 createSessionInternalLocked(serviceState.service, sessionToken, mUserId); 2124 } 2125 2126 for (TvInputState inputState : userState.inputMap.values()) { 2127 if (inputState.info.getComponent().equals(component) 2128 && inputState.state != INPUT_STATE_CONNECTED) { 2129 notifyInputStateChangedLocked(userState, inputState.info.getId(), 2130 inputState.state, null); 2131 } 2132 } 2133 2134 if (serviceState.isHardware) { 2135 serviceState.hardwareInputList.clear(); 2136 for (TvInputHardwareInfo hardware : mTvInputHardwareManager.getHardwareList()) { 2137 try { 2138 serviceState.service.notifyHardwareAdded(hardware); 2139 } catch (RemoteException e) { 2140 Slog.e(TAG, "error in notifyHardwareAdded", e); 2141 } 2142 } 2143 for (HdmiDeviceInfo device : mTvInputHardwareManager.getHdmiDeviceList()) { 2144 try { 2145 serviceState.service.notifyHdmiDeviceAdded(device); 2146 } catch (RemoteException e) { 2147 Slog.e(TAG, "error in notifyHdmiDeviceAdded", e); 2148 } 2149 } 2150 } 2151 } 2152 } 2153 2154 @Override 2155 public void onServiceDisconnected(ComponentName component) { 2156 if (DEBUG) { 2157 Slog.d(TAG, "onServiceDisconnected(component=" + component + ")"); 2158 } 2159 if (!mComponent.equals(component)) { 2160 throw new IllegalArgumentException("Mismatched ComponentName: " 2161 + mComponent + " (expected), " + component + " (actual)."); 2162 } 2163 synchronized (mLock) { 2164 UserState userState = getOrCreateUserStateLocked(mUserId); 2165 ServiceState serviceState = userState.serviceStateMap.get(mComponent); 2166 if (serviceState != null) { 2167 serviceState.reconnecting = true; 2168 serviceState.bound = false; 2169 serviceState.service = null; 2170 serviceState.callback = null; 2171 2172 abortPendingCreateSessionRequestsLocked(serviceState, null, mUserId); 2173 } 2174 } 2175 } 2176 } 2177 2178 private final class ServiceCallback extends ITvInputServiceCallback.Stub { 2179 private final ComponentName mComponent; 2180 private final int mUserId; 2181 2182 ServiceCallback(ComponentName component, int userId) { 2183 mComponent = component; 2184 mUserId = userId; 2185 } 2186 2187 private void ensureHardwarePermission() { 2188 if (mContext.checkCallingPermission(android.Manifest.permission.TV_INPUT_HARDWARE) 2189 != PackageManager.PERMISSION_GRANTED) { 2190 throw new SecurityException("The caller does not have hardware permission"); 2191 } 2192 } 2193 2194 private void ensureValidInput(TvInputInfo inputInfo) { 2195 if (inputInfo.getId() == null || !mComponent.equals(inputInfo.getComponent())) { 2196 throw new IllegalArgumentException("Invalid TvInputInfo"); 2197 } 2198 } 2199 2200 private void addHardwareInputLocked(TvInputInfo inputInfo) { 2201 ServiceState serviceState = getServiceStateLocked(mComponent, mUserId); 2202 serviceState.hardwareInputList.add(inputInfo); 2203 buildTvInputListLocked(mUserId, null); 2204 } 2205 2206 public void addHardwareInput(int deviceId, TvInputInfo inputInfo) { 2207 ensureHardwarePermission(); 2208 ensureValidInput(inputInfo); 2209 synchronized (mLock) { 2210 mTvInputHardwareManager.addHardwareInput(deviceId, inputInfo); 2211 addHardwareInputLocked(inputInfo); 2212 } 2213 } 2214 2215 public void addHdmiInput(int id, TvInputInfo inputInfo) { 2216 ensureHardwarePermission(); 2217 ensureValidInput(inputInfo); 2218 synchronized (mLock) { 2219 mTvInputHardwareManager.addHdmiInput(id, inputInfo); 2220 addHardwareInputLocked(inputInfo); 2221 } 2222 } 2223 2224 public void removeHardwareInput(String inputId) { 2225 ensureHardwarePermission(); 2226 synchronized (mLock) { 2227 ServiceState serviceState = getServiceStateLocked(mComponent, mUserId); 2228 boolean removed = false; 2229 for (Iterator<TvInputInfo> it = serviceState.hardwareInputList.iterator(); 2230 it.hasNext(); ) { 2231 if (it.next().getId().equals(inputId)) { 2232 it.remove(); 2233 removed = true; 2234 break; 2235 } 2236 } 2237 if (removed) { 2238 buildTvInputListLocked(mUserId, null); 2239 mTvInputHardwareManager.removeHardwareInput(inputId); 2240 } else { 2241 Slog.e(TAG, "failed to remove input " + inputId); 2242 } 2243 } 2244 } 2245 } 2246 2247 private final class SessionCallback extends ITvInputSessionCallback.Stub { 2248 private final SessionState mSessionState; 2249 private final InputChannel[] mChannels; 2250 2251 SessionCallback(SessionState sessionState, InputChannel[] channels) { 2252 mSessionState = sessionState; 2253 mChannels = channels; 2254 } 2255 2256 @Override 2257 public void onSessionCreated(ITvInputSession session, IBinder hardwareSessionToken) { 2258 if (DEBUG) { 2259 Slog.d(TAG, "onSessionCreated(inputId=" + mSessionState.inputId + ")"); 2260 } 2261 synchronized (mLock) { 2262 mSessionState.session = session; 2263 mSessionState.hardwareSessionToken = hardwareSessionToken; 2264 if (session != null && addSessionTokenToClientStateLocked(session)) { 2265 sendSessionTokenToClientLocked(mSessionState.client, 2266 mSessionState.inputId, mSessionState.sessionToken, mChannels[0], 2267 mSessionState.seq); 2268 } else { 2269 removeSessionStateLocked(mSessionState.sessionToken, mSessionState.userId); 2270 sendSessionTokenToClientLocked(mSessionState.client, 2271 mSessionState.inputId, null, null, mSessionState.seq); 2272 } 2273 mChannels[0].dispose(); 2274 } 2275 } 2276 2277 private boolean addSessionTokenToClientStateLocked(ITvInputSession session) { 2278 try { 2279 session.asBinder().linkToDeath(mSessionState, 0); 2280 } catch (RemoteException e) { 2281 Slog.e(TAG, "session process has already died", e); 2282 return false; 2283 } 2284 2285 IBinder clientToken = mSessionState.client.asBinder(); 2286 UserState userState = getOrCreateUserStateLocked(mSessionState.userId); 2287 ClientState clientState = userState.clientStateMap.get(clientToken); 2288 if (clientState == null) { 2289 clientState = new ClientState(clientToken, mSessionState.userId); 2290 try { 2291 clientToken.linkToDeath(clientState, 0); 2292 } catch (RemoteException e) { 2293 Slog.e(TAG, "client process has already died", e); 2294 return false; 2295 } 2296 userState.clientStateMap.put(clientToken, clientState); 2297 } 2298 clientState.sessionTokens.add(mSessionState.sessionToken); 2299 return true; 2300 } 2301 2302 @Override 2303 public void onChannelRetuned(Uri channelUri) { 2304 synchronized (mLock) { 2305 if (DEBUG) { 2306 Slog.d(TAG, "onChannelRetuned(" + channelUri + ")"); 2307 } 2308 if (mSessionState.session == null || mSessionState.client == null) { 2309 return; 2310 } 2311 try { 2312 // TODO: Consider adding this channel change in the watch log. When we do 2313 // that, how we can protect the watch log from malicious tv inputs should 2314 // be addressed. e.g. add a field which represents where the channel change 2315 // originated from. 2316 mSessionState.client.onChannelRetuned(channelUri, mSessionState.seq); 2317 } catch (RemoteException e) { 2318 Slog.e(TAG, "error in onChannelRetuned", e); 2319 } 2320 } 2321 } 2322 2323 @Override 2324 public void onTracksChanged(List<TvTrackInfo> tracks) { 2325 synchronized (mLock) { 2326 if (DEBUG) { 2327 Slog.d(TAG, "onTracksChanged(" + tracks + ")"); 2328 } 2329 if (mSessionState.session == null || mSessionState.client == null) { 2330 return; 2331 } 2332 try { 2333 mSessionState.client.onTracksChanged(tracks, mSessionState.seq); 2334 } catch (RemoteException e) { 2335 Slog.e(TAG, "error in onTracksChanged", e); 2336 } 2337 } 2338 } 2339 2340 @Override 2341 public void onTrackSelected(int type, String trackId) { 2342 synchronized (mLock) { 2343 if (DEBUG) { 2344 Slog.d(TAG, "onTrackSelected(type=" + type + ", trackId=" + trackId + ")"); 2345 } 2346 if (mSessionState.session == null || mSessionState.client == null) { 2347 return; 2348 } 2349 try { 2350 mSessionState.client.onTrackSelected(type, trackId, mSessionState.seq); 2351 } catch (RemoteException e) { 2352 Slog.e(TAG, "error in onTrackSelected", e); 2353 } 2354 } 2355 } 2356 2357 @Override 2358 public void onVideoAvailable() { 2359 synchronized (mLock) { 2360 if (DEBUG) { 2361 Slog.d(TAG, "onVideoAvailable()"); 2362 } 2363 if (mSessionState.session == null || mSessionState.client == null) { 2364 return; 2365 } 2366 try { 2367 mSessionState.client.onVideoAvailable(mSessionState.seq); 2368 } catch (RemoteException e) { 2369 Slog.e(TAG, "error in onVideoAvailable", e); 2370 } 2371 } 2372 } 2373 2374 @Override 2375 public void onVideoUnavailable(int reason) { 2376 synchronized (mLock) { 2377 if (DEBUG) { 2378 Slog.d(TAG, "onVideoUnavailable(" + reason + ")"); 2379 } 2380 if (mSessionState.session == null || mSessionState.client == null) { 2381 return; 2382 } 2383 try { 2384 mSessionState.client.onVideoUnavailable(reason, mSessionState.seq); 2385 } catch (RemoteException e) { 2386 Slog.e(TAG, "error in onVideoUnavailable", e); 2387 } 2388 } 2389 } 2390 2391 @Override 2392 public void onContentAllowed() { 2393 synchronized (mLock) { 2394 if (DEBUG) { 2395 Slog.d(TAG, "onContentAllowed()"); 2396 } 2397 if (mSessionState.session == null || mSessionState.client == null) { 2398 return; 2399 } 2400 try { 2401 mSessionState.client.onContentAllowed(mSessionState.seq); 2402 } catch (RemoteException e) { 2403 Slog.e(TAG, "error in onContentAllowed", e); 2404 } 2405 } 2406 } 2407 2408 @Override 2409 public void onContentBlocked(String rating) { 2410 synchronized (mLock) { 2411 if (DEBUG) { 2412 Slog.d(TAG, "onContentBlocked()"); 2413 } 2414 if (mSessionState.session == null || mSessionState.client == null) { 2415 return; 2416 } 2417 try { 2418 mSessionState.client.onContentBlocked(rating, mSessionState.seq); 2419 } catch (RemoteException e) { 2420 Slog.e(TAG, "error in onContentBlocked", e); 2421 } 2422 } 2423 } 2424 2425 @Override 2426 public void onLayoutSurface(int left, int top, int right, int bottom) { 2427 synchronized (mLock) { 2428 if (DEBUG) { 2429 Slog.d(TAG, "onLayoutSurface (left=" + left + ", top=" + top 2430 + ", right=" + right + ", bottom=" + bottom + ",)"); 2431 } 2432 if (mSessionState.session == null || mSessionState.client == null) { 2433 return; 2434 } 2435 try { 2436 mSessionState.client.onLayoutSurface(left, top, right, bottom, 2437 mSessionState.seq); 2438 } catch (RemoteException e) { 2439 Slog.e(TAG, "error in onLayoutSurface", e); 2440 } 2441 } 2442 } 2443 2444 @Override 2445 public void onSessionEvent(String eventType, Bundle eventArgs) { 2446 synchronized (mLock) { 2447 if (DEBUG) { 2448 Slog.d(TAG, "onEvent(eventType=" + eventType + ", eventArgs=" + eventArgs 2449 + ")"); 2450 } 2451 if (mSessionState.session == null || mSessionState.client == null) { 2452 return; 2453 } 2454 try { 2455 mSessionState.client.onSessionEvent(eventType, eventArgs, mSessionState.seq); 2456 } catch (RemoteException e) { 2457 Slog.e(TAG, "error in onSessionEvent", e); 2458 } 2459 } 2460 } 2461 2462 @Override 2463 public void onTimeShiftStatusChanged(int status) { 2464 synchronized (mLock) { 2465 if (DEBUG) { 2466 Slog.d(TAG, "onTimeShiftStatusChanged(status=" + status + ")"); 2467 } 2468 if (mSessionState.session == null || mSessionState.client == null) { 2469 return; 2470 } 2471 try { 2472 mSessionState.client.onTimeShiftStatusChanged(status, mSessionState.seq); 2473 } catch (RemoteException e) { 2474 Slog.e(TAG, "error in onTimeShiftStatusChanged", e); 2475 } 2476 } 2477 } 2478 2479 @Override 2480 public void onTimeShiftStartPositionChanged(long timeMs) { 2481 synchronized (mLock) { 2482 if (DEBUG) { 2483 Slog.d(TAG, "onTimeShiftStartPositionChanged(timeMs=" + timeMs + ")"); 2484 } 2485 if (mSessionState.session == null || mSessionState.client == null) { 2486 return; 2487 } 2488 try { 2489 mSessionState.client.onTimeShiftStartPositionChanged(timeMs, mSessionState.seq); 2490 } catch (RemoteException e) { 2491 Slog.e(TAG, "error in onTimeShiftStartPositionChanged", e); 2492 } 2493 } 2494 } 2495 2496 @Override 2497 public void onTimeShiftCurrentPositionChanged(long timeMs) { 2498 synchronized (mLock) { 2499 if (DEBUG) { 2500 Slog.d(TAG, "onTimeShiftCurrentPositionChanged(timeMs=" + timeMs + ")"); 2501 } 2502 if (mSessionState.session == null || mSessionState.client == null) { 2503 return; 2504 } 2505 try { 2506 mSessionState.client.onTimeShiftCurrentPositionChanged(timeMs, 2507 mSessionState.seq); 2508 } catch (RemoteException e) { 2509 Slog.e(TAG, "error in onTimeShiftCurrentPositionChanged", e); 2510 } 2511 } 2512 } 2513 2514 // For the recording session only 2515 @Override 2516 public void onTuned(Uri channelUri) { 2517 synchronized (mLock) { 2518 if (DEBUG) { 2519 Slog.d(TAG, "onTuned()"); 2520 } 2521 if (mSessionState.session == null || mSessionState.client == null) { 2522 return; 2523 } 2524 try { 2525 mSessionState.client.onTuned(mSessionState.seq, channelUri); 2526 } catch (RemoteException e) { 2527 Slog.e(TAG, "error in onTuned", e); 2528 } 2529 } 2530 } 2531 2532 // For the recording session only 2533 @Override 2534 public void onRecordingStopped(Uri recordedProgramUri) { 2535 synchronized (mLock) { 2536 if (DEBUG) { 2537 Slog.d(TAG, "onRecordingStopped(recordedProgramUri=" + recordedProgramUri 2538 + ")"); 2539 } 2540 if (mSessionState.session == null || mSessionState.client == null) { 2541 return; 2542 } 2543 try { 2544 mSessionState.client.onRecordingStopped(recordedProgramUri, mSessionState.seq); 2545 } catch (RemoteException e) { 2546 Slog.e(TAG, "error in onRecordingStopped", e); 2547 } 2548 } 2549 } 2550 2551 // For the recording session only 2552 @Override 2553 public void onError(int error) { 2554 synchronized (mLock) { 2555 if (DEBUG) { 2556 Slog.d(TAG, "onError(error=" + error + ")"); 2557 } 2558 if (mSessionState.session == null || mSessionState.client == null) { 2559 return; 2560 } 2561 try { 2562 mSessionState.client.onError(error, mSessionState.seq); 2563 } catch (RemoteException e) { 2564 Slog.e(TAG, "error in onError", e); 2565 } 2566 } 2567 } 2568 } 2569 2570 private static final class WatchLogHandler extends Handler { 2571 // There are only two kinds of watch events that can happen on the system: 2572 // 1. The current TV input session is tuned to a new channel. 2573 // 2. The session is released for some reason. 2574 // The former indicates the end of the previous log entry, if any, followed by the start of 2575 // a new entry. The latter indicates the end of the most recent entry for the given session. 2576 // Here the system supplies the database the smallest set of information only that is 2577 // sufficient to consolidate the log entries while minimizing database operations in the 2578 // system service. 2579 static final int MSG_LOG_WATCH_START = 1; 2580 static final int MSG_LOG_WATCH_END = 2; 2581 static final int MSG_SWITCH_CONTENT_RESOLVER = 3; 2582 2583 private ContentResolver mContentResolver; 2584 2585 WatchLogHandler(ContentResolver contentResolver, Looper looper) { 2586 super(looper); 2587 mContentResolver = contentResolver; 2588 } 2589 2590 @Override 2591 public void handleMessage(Message msg) { 2592 switch (msg.what) { 2593 case MSG_LOG_WATCH_START: { 2594 SomeArgs args = (SomeArgs) msg.obj; 2595 String packageName = (String) args.arg1; 2596 long watchStartTime = (long) args.arg2; 2597 long channelId = (long) args.arg3; 2598 Bundle tuneParams = (Bundle) args.arg4; 2599 IBinder sessionToken = (IBinder) args.arg5; 2600 2601 ContentValues values = new ContentValues(); 2602 values.put(TvContract.WatchedPrograms.COLUMN_PACKAGE_NAME, packageName); 2603 values.put(TvContract.WatchedPrograms.COLUMN_WATCH_START_TIME_UTC_MILLIS, 2604 watchStartTime); 2605 values.put(TvContract.WatchedPrograms.COLUMN_CHANNEL_ID, channelId); 2606 if (tuneParams != null) { 2607 values.put(TvContract.WatchedPrograms.COLUMN_INTERNAL_TUNE_PARAMS, 2608 encodeTuneParams(tuneParams)); 2609 } 2610 values.put(TvContract.WatchedPrograms.COLUMN_INTERNAL_SESSION_TOKEN, 2611 sessionToken.toString()); 2612 2613 mContentResolver.insert(TvContract.WatchedPrograms.CONTENT_URI, values); 2614 args.recycle(); 2615 break; 2616 } 2617 case MSG_LOG_WATCH_END: { 2618 SomeArgs args = (SomeArgs) msg.obj; 2619 IBinder sessionToken = (IBinder) args.arg1; 2620 long watchEndTime = (long) args.arg2; 2621 2622 ContentValues values = new ContentValues(); 2623 values.put(TvContract.WatchedPrograms.COLUMN_WATCH_END_TIME_UTC_MILLIS, 2624 watchEndTime); 2625 values.put(TvContract.WatchedPrograms.COLUMN_INTERNAL_SESSION_TOKEN, 2626 sessionToken.toString()); 2627 2628 mContentResolver.insert(TvContract.WatchedPrograms.CONTENT_URI, values); 2629 args.recycle(); 2630 break; 2631 } 2632 case MSG_SWITCH_CONTENT_RESOLVER: { 2633 mContentResolver = (ContentResolver) msg.obj; 2634 break; 2635 } 2636 default: { 2637 Slog.w(TAG, "unhandled message code: " + msg.what); 2638 break; 2639 } 2640 } 2641 } 2642 2643 private String encodeTuneParams(Bundle tuneParams) { 2644 StringBuilder builder = new StringBuilder(); 2645 Set<String> keySet = tuneParams.keySet(); 2646 Iterator<String> it = keySet.iterator(); 2647 while (it.hasNext()) { 2648 String key = it.next(); 2649 Object value = tuneParams.get(key); 2650 if (value == null) { 2651 continue; 2652 } 2653 builder.append(replaceEscapeCharacters(key)); 2654 builder.append("="); 2655 builder.append(replaceEscapeCharacters(value.toString())); 2656 if (it.hasNext()) { 2657 builder.append(", "); 2658 } 2659 } 2660 return builder.toString(); 2661 } 2662 2663 private String replaceEscapeCharacters(String src) { 2664 final char ESCAPE_CHARACTER = '%'; 2665 final String ENCODING_TARGET_CHARACTERS = "%=,"; 2666 StringBuilder builder = new StringBuilder(); 2667 for (char ch : src.toCharArray()) { 2668 if (ENCODING_TARGET_CHARACTERS.indexOf(ch) >= 0) { 2669 builder.append(ESCAPE_CHARACTER); 2670 } 2671 builder.append(ch); 2672 } 2673 return builder.toString(); 2674 } 2675 } 2676 2677 private final class HardwareListener implements TvInputHardwareManager.Listener { 2678 @Override 2679 public void onStateChanged(String inputId, int state) { 2680 synchronized (mLock) { 2681 setStateLocked(inputId, state, mCurrentUserId); 2682 } 2683 } 2684 2685 @Override 2686 public void onHardwareDeviceAdded(TvInputHardwareInfo info) { 2687 synchronized (mLock) { 2688 UserState userState = getOrCreateUserStateLocked(mCurrentUserId); 2689 // Broadcast the event to all hardware inputs. 2690 for (ServiceState serviceState : userState.serviceStateMap.values()) { 2691 if (!serviceState.isHardware || serviceState.service == null) continue; 2692 try { 2693 serviceState.service.notifyHardwareAdded(info); 2694 } catch (RemoteException e) { 2695 Slog.e(TAG, "error in notifyHardwareAdded", e); 2696 } 2697 } 2698 } 2699 } 2700 2701 @Override 2702 public void onHardwareDeviceRemoved(TvInputHardwareInfo info) { 2703 synchronized (mLock) { 2704 UserState userState = getOrCreateUserStateLocked(mCurrentUserId); 2705 // Broadcast the event to all hardware inputs. 2706 for (ServiceState serviceState : userState.serviceStateMap.values()) { 2707 if (!serviceState.isHardware || serviceState.service == null) continue; 2708 try { 2709 serviceState.service.notifyHardwareRemoved(info); 2710 } catch (RemoteException e) { 2711 Slog.e(TAG, "error in notifyHardwareRemoved", e); 2712 } 2713 } 2714 } 2715 } 2716 2717 @Override 2718 public void onHdmiDeviceAdded(HdmiDeviceInfo deviceInfo) { 2719 synchronized (mLock) { 2720 UserState userState = getOrCreateUserStateLocked(mCurrentUserId); 2721 // Broadcast the event to all hardware inputs. 2722 for (ServiceState serviceState : userState.serviceStateMap.values()) { 2723 if (!serviceState.isHardware || serviceState.service == null) continue; 2724 try { 2725 serviceState.service.notifyHdmiDeviceAdded(deviceInfo); 2726 } catch (RemoteException e) { 2727 Slog.e(TAG, "error in notifyHdmiDeviceAdded", e); 2728 } 2729 } 2730 } 2731 } 2732 2733 @Override 2734 public void onHdmiDeviceRemoved(HdmiDeviceInfo deviceInfo) { 2735 synchronized (mLock) { 2736 UserState userState = getOrCreateUserStateLocked(mCurrentUserId); 2737 // Broadcast the event to all hardware inputs. 2738 for (ServiceState serviceState : userState.serviceStateMap.values()) { 2739 if (!serviceState.isHardware || serviceState.service == null) continue; 2740 try { 2741 serviceState.service.notifyHdmiDeviceRemoved(deviceInfo); 2742 } catch (RemoteException e) { 2743 Slog.e(TAG, "error in notifyHdmiDeviceRemoved", e); 2744 } 2745 } 2746 } 2747 } 2748 2749 @Override 2750 public void onHdmiDeviceUpdated(String inputId, HdmiDeviceInfo deviceInfo) { 2751 synchronized (mLock) { 2752 Integer state; 2753 switch (deviceInfo.getDevicePowerStatus()) { 2754 case HdmiControlManager.POWER_STATUS_ON: 2755 state = INPUT_STATE_CONNECTED; 2756 break; 2757 case HdmiControlManager.POWER_STATUS_STANDBY: 2758 case HdmiControlManager.POWER_STATUS_TRANSIENT_TO_ON: 2759 case HdmiControlManager.POWER_STATUS_TRANSIENT_TO_STANDBY: 2760 state = INPUT_STATE_CONNECTED_STANDBY; 2761 break; 2762 case HdmiControlManager.POWER_STATUS_UNKNOWN: 2763 default: 2764 state = null; 2765 break; 2766 } 2767 if (state != null) { 2768 setStateLocked(inputId, state, mCurrentUserId); 2769 } 2770 } 2771 } 2772 } 2773 2774 private static class SessionNotFoundException extends IllegalArgumentException { 2775 public SessionNotFoundException(String name) { 2776 super(name); 2777 } 2778 } 2779} 2780