HdmiCecLocalDevice.java revision 4480efa05aa5dd44f1432c3260be263546daf838
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.hdmi; 18 19import android.hardware.hdmi.HdmiDeviceInfo; 20import android.hardware.input.InputManager; 21import android.os.Handler; 22import android.os.Looper; 23import android.os.Message; 24import android.os.SystemClock; 25import android.util.Slog; 26import android.view.InputDevice; 27import android.view.KeyCharacterMap; 28import android.view.KeyEvent; 29 30import com.android.internal.annotations.GuardedBy; 31import com.android.internal.util.IndentingPrintWriter; 32import com.android.server.hdmi.HdmiAnnotations.ServiceThreadOnly; 33 34import java.util.ArrayList; 35import java.util.Collections; 36import java.util.Iterator; 37import java.util.LinkedList; 38import java.util.List; 39 40/** 41 * Class that models a logical CEC device hosted in this system. Handles initialization, 42 * CEC commands that call for actions customized per device type. 43 */ 44abstract class HdmiCecLocalDevice { 45 private static final String TAG = "HdmiCecLocalDevice"; 46 47 private static final int MSG_DISABLE_DEVICE_TIMEOUT = 1; 48 private static final int MSG_USER_CONTROL_RELEASE_TIMEOUT = 2; 49 // Timeout in millisecond for device clean up (5s). 50 // Normal actions timeout is 2s but some of them would have several sequence of timeout. 51 private static final int DEVICE_CLEANUP_TIMEOUT = 5000; 52 // Within the timer, a received <User Control Pressed> will start "Press and Hold" behavior. 53 // When it expires, we can assume <User Control Release> is received. 54 private static final int FOLLOWER_SAFETY_TIMEOUT = 550; 55 56 protected final HdmiControlService mService; 57 protected final int mDeviceType; 58 protected int mAddress; 59 protected int mPreferredAddress; 60 protected HdmiDeviceInfo mDeviceInfo; 61 protected int mLastKeycode = HdmiCecKeycode.UNSUPPORTED_KEYCODE; 62 protected int mLastKeyRepeatCount = 0; 63 64 static class ActiveSource { 65 int logicalAddress; 66 int physicalAddress; 67 68 public ActiveSource() { 69 invalidate(); 70 } 71 public ActiveSource(int logical, int physical) { 72 logicalAddress = logical; 73 physicalAddress = physical; 74 } 75 public static ActiveSource of(int logical, int physical) { 76 return new ActiveSource(logical, physical); 77 } 78 public boolean isValid() { 79 return HdmiUtils.isValidAddress(logicalAddress); 80 } 81 public void invalidate() { 82 logicalAddress = Constants.ADDR_INVALID; 83 physicalAddress = Constants.INVALID_PHYSICAL_ADDRESS; 84 } 85 public boolean equals(int logical, int physical) { 86 return logicalAddress == logical && physicalAddress == physical; 87 } 88 @Override 89 public boolean equals(Object obj) { 90 if (obj instanceof ActiveSource) { 91 ActiveSource that = (ActiveSource) obj; 92 return that.logicalAddress == logicalAddress && 93 that.physicalAddress == physicalAddress; 94 } 95 return false; 96 } 97 @Override 98 public int hashCode() { 99 return logicalAddress * 29 + physicalAddress; 100 } 101 @Override 102 public String toString() { 103 StringBuffer s = new StringBuffer(); 104 String logicalAddressString = (logicalAddress == Constants.ADDR_INVALID) 105 ? "invalid" : String.format("0x%02x", logicalAddress); 106 s.append("logical_address: ").append(logicalAddressString); 107 String physicalAddressString = (physicalAddress == Constants.INVALID_PHYSICAL_ADDRESS) 108 ? "invalid" : String.format("0x%04x", physicalAddress); 109 s.append(", physical_address: ").append(physicalAddressString); 110 return s.toString(); 111 } 112 } 113 // Logical address of the active source. 114 @GuardedBy("mLock") 115 protected final ActiveSource mActiveSource = new ActiveSource(); 116 117 // Active routing path. Physical address of the active source but not all the time, such as 118 // when the new active source does not claim itself to be one. Note that we don't keep 119 // the active port id (or active input) since it can be gotten by {@link #pathToPortId(int)}. 120 @GuardedBy("mLock") 121 private int mActiveRoutingPath; 122 123 protected final HdmiCecMessageCache mCecMessageCache = new HdmiCecMessageCache(); 124 protected final Object mLock; 125 126 // A collection of FeatureAction. 127 // Note that access to this collection should happen in service thread. 128 private final LinkedList<HdmiCecFeatureAction> mActions = new LinkedList<>(); 129 130 private final Handler mHandler = new Handler () { 131 @Override 132 public void handleMessage(Message msg) { 133 switch (msg.what) { 134 case MSG_DISABLE_DEVICE_TIMEOUT: 135 handleDisableDeviceTimeout(); 136 break; 137 case MSG_USER_CONTROL_RELEASE_TIMEOUT: 138 handleUserControlReleased(); 139 break; 140 } 141 } 142 }; 143 144 /** 145 * A callback interface to get notified when all pending action is cleared. 146 * It can be called when timeout happened. 147 */ 148 interface PendingActionClearedCallback { 149 void onCleared(HdmiCecLocalDevice device); 150 } 151 152 protected PendingActionClearedCallback mPendingActionClearedCallback; 153 154 protected HdmiCecLocalDevice(HdmiControlService service, int deviceType) { 155 mService = service; 156 mDeviceType = deviceType; 157 mAddress = Constants.ADDR_UNREGISTERED; 158 mLock = service.getServiceLock(); 159 } 160 161 // Factory method that returns HdmiCecLocalDevice of corresponding type. 162 static HdmiCecLocalDevice create(HdmiControlService service, int deviceType) { 163 switch (deviceType) { 164 case HdmiDeviceInfo.DEVICE_TV: 165 return new HdmiCecLocalDeviceTv(service); 166 case HdmiDeviceInfo.DEVICE_PLAYBACK: 167 return new HdmiCecLocalDevicePlayback(service); 168 default: 169 return null; 170 } 171 } 172 173 @ServiceThreadOnly 174 void init() { 175 assertRunOnServiceThread(); 176 mPreferredAddress = getPreferredAddress(); 177 } 178 179 /** 180 * Called once a logical address of the local device is allocated. 181 */ 182 protected abstract void onAddressAllocated(int logicalAddress, int reason); 183 184 /** 185 * Get the preferred logical address from system properties. 186 */ 187 protected abstract int getPreferredAddress(); 188 189 /** 190 * Set the preferred logical address to system properties. 191 */ 192 protected abstract void setPreferredAddress(int addr); 193 194 /** 195 * Dispatch incoming message. 196 * 197 * @param message incoming message 198 * @return true if consumed a message; otherwise, return false. 199 */ 200 @ServiceThreadOnly 201 boolean dispatchMessage(HdmiCecMessage message) { 202 assertRunOnServiceThread(); 203 int dest = message.getDestination(); 204 if (dest != mAddress && dest != Constants.ADDR_BROADCAST) { 205 return false; 206 } 207 // Cache incoming message. Note that it caches only white-listed one. 208 mCecMessageCache.cacheMessage(message); 209 return onMessage(message); 210 } 211 212 @ServiceThreadOnly 213 protected final boolean onMessage(HdmiCecMessage message) { 214 assertRunOnServiceThread(); 215 if (dispatchMessageToAction(message)) { 216 return true; 217 } 218 switch (message.getOpcode()) { 219 case Constants.MESSAGE_ACTIVE_SOURCE: 220 return handleActiveSource(message); 221 case Constants.MESSAGE_INACTIVE_SOURCE: 222 return handleInactiveSource(message); 223 case Constants.MESSAGE_REQUEST_ACTIVE_SOURCE: 224 return handleRequestActiveSource(message); 225 case Constants.MESSAGE_GET_MENU_LANGUAGE: 226 return handleGetMenuLanguage(message); 227 case Constants.MESSAGE_GIVE_PHYSICAL_ADDRESS: 228 return handleGivePhysicalAddress(); 229 case Constants.MESSAGE_GIVE_OSD_NAME: 230 return handleGiveOsdName(message); 231 case Constants.MESSAGE_GIVE_DEVICE_VENDOR_ID: 232 return handleGiveDeviceVendorId(); 233 case Constants.MESSAGE_GET_CEC_VERSION: 234 return handleGetCecVersion(message); 235 case Constants.MESSAGE_REPORT_PHYSICAL_ADDRESS: 236 return handleReportPhysicalAddress(message); 237 case Constants.MESSAGE_ROUTING_CHANGE: 238 return handleRoutingChange(message); 239 case Constants.MESSAGE_ROUTING_INFORMATION: 240 return handleRoutingInformation(message); 241 case Constants.MESSAGE_INITIATE_ARC: 242 return handleInitiateArc(message); 243 case Constants.MESSAGE_TERMINATE_ARC: 244 return handleTerminateArc(message); 245 case Constants.MESSAGE_SET_SYSTEM_AUDIO_MODE: 246 return handleSetSystemAudioMode(message); 247 case Constants.MESSAGE_SYSTEM_AUDIO_MODE_STATUS: 248 return handleSystemAudioModeStatus(message); 249 case Constants.MESSAGE_REPORT_AUDIO_STATUS: 250 return handleReportAudioStatus(message); 251 case Constants.MESSAGE_STANDBY: 252 return handleStandby(message); 253 case Constants.MESSAGE_TEXT_VIEW_ON: 254 return handleTextViewOn(message); 255 case Constants.MESSAGE_IMAGE_VIEW_ON: 256 return handleImageViewOn(message); 257 case Constants.MESSAGE_USER_CONTROL_PRESSED: 258 return handleUserControlPressed(message); 259 case Constants.MESSAGE_USER_CONTROL_RELEASED: 260 return handleUserControlReleased(); 261 case Constants.MESSAGE_SET_STREAM_PATH: 262 return handleSetStreamPath(message); 263 case Constants.MESSAGE_GIVE_DEVICE_POWER_STATUS: 264 return handleGiveDevicePowerStatus(message); 265 case Constants.MESSAGE_MENU_REQUEST: 266 return handleGiveDeviceMenuStatus(message); 267 case Constants.MESSAGE_VENDOR_COMMAND: 268 return handleVendorCommand(message); 269 case Constants.MESSAGE_VENDOR_COMMAND_WITH_ID: 270 return handleVendorCommandWithId(message); 271 case Constants.MESSAGE_SET_OSD_NAME: 272 return handleSetOsdName(message); 273 case Constants.MESSAGE_RECORD_TV_SCREEN: 274 return handleRecordTvScreen(message); 275 case Constants.MESSAGE_TIMER_CLEARED_STATUS: 276 return handleTimerClearedStatus(message); 277 case Constants.MESSAGE_REPORT_POWER_STATUS: 278 return handleReportPowerStatus(message); 279 case Constants.MESSAGE_TIMER_STATUS: 280 return handleTimerStatus(message); 281 case Constants.MESSAGE_RECORD_STATUS: 282 return handleRecordStatus(message); 283 default: 284 return false; 285 } 286 } 287 288 @ServiceThreadOnly 289 private boolean dispatchMessageToAction(HdmiCecMessage message) { 290 assertRunOnServiceThread(); 291 for (HdmiCecFeatureAction action : mActions) { 292 if (action.processCommand(message)) { 293 return true; 294 } 295 } 296 return false; 297 } 298 299 @ServiceThreadOnly 300 protected boolean handleGivePhysicalAddress() { 301 assertRunOnServiceThread(); 302 303 int physicalAddress = mService.getPhysicalAddress(); 304 HdmiCecMessage cecMessage = HdmiCecMessageBuilder.buildReportPhysicalAddressCommand( 305 mAddress, physicalAddress, mDeviceType); 306 mService.sendCecCommand(cecMessage); 307 return true; 308 } 309 310 @ServiceThreadOnly 311 protected boolean handleGiveDeviceVendorId() { 312 assertRunOnServiceThread(); 313 int vendorId = mService.getVendorId(); 314 HdmiCecMessage cecMessage = HdmiCecMessageBuilder.buildDeviceVendorIdCommand( 315 mAddress, vendorId); 316 mService.sendCecCommand(cecMessage); 317 return true; 318 } 319 320 @ServiceThreadOnly 321 protected boolean handleGetCecVersion(HdmiCecMessage message) { 322 assertRunOnServiceThread(); 323 int version = mService.getCecVersion(); 324 HdmiCecMessage cecMessage = HdmiCecMessageBuilder.buildCecVersion(message.getDestination(), 325 message.getSource(), version); 326 mService.sendCecCommand(cecMessage); 327 return true; 328 } 329 330 @ServiceThreadOnly 331 protected boolean handleActiveSource(HdmiCecMessage message) { 332 return false; 333 } 334 335 @ServiceThreadOnly 336 protected boolean handleInactiveSource(HdmiCecMessage message) { 337 return false; 338 } 339 340 @ServiceThreadOnly 341 protected boolean handleRequestActiveSource(HdmiCecMessage message) { 342 return false; 343 } 344 345 @ServiceThreadOnly 346 protected boolean handleGetMenuLanguage(HdmiCecMessage message) { 347 assertRunOnServiceThread(); 348 Slog.w(TAG, "Only TV can handle <Get Menu Language>:" + message.toString()); 349 // 'return false' will cause to reply with <Feature Abort>. 350 return false; 351 } 352 353 @ServiceThreadOnly 354 protected boolean handleGiveOsdName(HdmiCecMessage message) { 355 assertRunOnServiceThread(); 356 // Note that since this method is called after logical address allocation is done, 357 // mDeviceInfo should not be null. 358 HdmiCecMessage cecMessage = HdmiCecMessageBuilder.buildSetOsdNameCommand( 359 mAddress, message.getSource(), mDeviceInfo.getDisplayName()); 360 if (cecMessage != null) { 361 mService.sendCecCommand(cecMessage); 362 } else { 363 Slog.w(TAG, "Failed to build <Get Osd Name>:" + mDeviceInfo.getDisplayName()); 364 } 365 return true; 366 } 367 368 protected boolean handleRoutingChange(HdmiCecMessage message) { 369 return false; 370 } 371 372 protected boolean handleRoutingInformation(HdmiCecMessage message) { 373 return false; 374 } 375 376 protected boolean handleReportPhysicalAddress(HdmiCecMessage message) { 377 return false; 378 } 379 380 protected boolean handleSystemAudioModeStatus(HdmiCecMessage message) { 381 return false; 382 } 383 384 protected boolean handleSetSystemAudioMode(HdmiCecMessage message) { 385 return false; 386 } 387 388 protected boolean handleTerminateArc(HdmiCecMessage message) { 389 return false; 390 } 391 392 protected boolean handleInitiateArc(HdmiCecMessage message) { 393 return false; 394 } 395 396 protected boolean handleReportAudioStatus(HdmiCecMessage message) { 397 return false; 398 } 399 400 @ServiceThreadOnly 401 protected boolean handleStandby(HdmiCecMessage message) { 402 assertRunOnServiceThread(); 403 // Seq #12 404 if (mService.isControlEnabled() && !mService.isProhibitMode() 405 && mService.isPowerOnOrTransient()) { 406 mService.standby(); 407 return true; 408 } 409 return false; 410 } 411 412 @ServiceThreadOnly 413 protected boolean handleUserControlPressed(HdmiCecMessage message) { 414 assertRunOnServiceThread(); 415 mHandler.removeMessages(MSG_USER_CONTROL_RELEASE_TIMEOUT); 416 if (mService.isPowerOnOrTransient() && isPowerOffOrToggleCommand(message)) { 417 mService.standby(); 418 return true; 419 } else if (mService.isPowerStandbyOrTransient() && isPowerOnOrToggleCommand(message)) { 420 mService.wakeUp(); 421 return true; 422 } 423 424 final long downTime = SystemClock.uptimeMillis(); 425 final byte[] params = message.getParams(); 426 // Note that we don't support parameterized keycode now. 427 // TODO: translate parameterized keycode as well. 428 final int keycode = HdmiCecKeycode.cecKeyToAndroidKey(params[0]); 429 int keyRepeatCount = 0; 430 if (mLastKeycode != HdmiCecKeycode.UNSUPPORTED_KEYCODE) { 431 if (keycode == mLastKeycode) { 432 keyRepeatCount = mLastKeyRepeatCount + 1; 433 } else { 434 injectKeyEvent(downTime, KeyEvent.ACTION_UP, mLastKeycode, 0); 435 } 436 } 437 mLastKeycode = keycode; 438 mLastKeyRepeatCount = keyRepeatCount; 439 440 if (keycode != HdmiCecKeycode.UNSUPPORTED_KEYCODE) { 441 injectKeyEvent(downTime, KeyEvent.ACTION_DOWN, keycode, keyRepeatCount); 442 mHandler.sendMessageDelayed(Message.obtain(mHandler, MSG_USER_CONTROL_RELEASE_TIMEOUT), 443 FOLLOWER_SAFETY_TIMEOUT); 444 return true; 445 } 446 return false; 447 } 448 449 @ServiceThreadOnly 450 protected boolean handleUserControlReleased() { 451 assertRunOnServiceThread(); 452 mHandler.removeMessages(MSG_USER_CONTROL_RELEASE_TIMEOUT); 453 mLastKeyRepeatCount = 0; 454 if (mLastKeycode != HdmiCecKeycode.UNSUPPORTED_KEYCODE) { 455 final long upTime = SystemClock.uptimeMillis(); 456 injectKeyEvent(upTime, KeyEvent.ACTION_UP, mLastKeycode, 0); 457 mLastKeycode = HdmiCecKeycode.UNSUPPORTED_KEYCODE; 458 return true; 459 } 460 return false; 461 } 462 463 static void injectKeyEvent(long time, int action, int keycode, int repeat) { 464 KeyEvent keyEvent = KeyEvent.obtain(time, time, action, keycode, 465 repeat, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FROM_SYSTEM, 466 InputDevice.SOURCE_HDMI, null); 467 InputManager.getInstance().injectInputEvent(keyEvent, 468 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC); 469 keyEvent.recycle(); 470 } 471 472 static boolean isPowerOnOrToggleCommand(HdmiCecMessage message) { 473 byte[] params = message.getParams(); 474 return message.getOpcode() == Constants.MESSAGE_USER_CONTROL_PRESSED 475 && (params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER 476 || params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER_ON_FUNCTION 477 || params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER_TOGGLE_FUNCTION); 478 } 479 480 static boolean isPowerOffOrToggleCommand(HdmiCecMessage message) { 481 byte[] params = message.getParams(); 482 return message.getOpcode() == Constants.MESSAGE_USER_CONTROL_PRESSED 483 && (params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER 484 || params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER_OFF_FUNCTION 485 || params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER_TOGGLE_FUNCTION); 486 } 487 488 protected boolean handleTextViewOn(HdmiCecMessage message) { 489 return false; 490 } 491 492 protected boolean handleImageViewOn(HdmiCecMessage message) { 493 return false; 494 } 495 496 protected boolean handleSetStreamPath(HdmiCecMessage message) { 497 return false; 498 } 499 500 protected boolean handleGiveDevicePowerStatus(HdmiCecMessage message) { 501 mService.sendCecCommand(HdmiCecMessageBuilder.buildReportPowerStatus( 502 mAddress, message.getSource(), mService.getPowerStatus())); 503 return true; 504 } 505 506 protected boolean handleGiveDeviceMenuStatus(HdmiCecMessage message) { 507 // Always report menu active to receive Remote Control. 508 mService.sendCecCommand(HdmiCecMessageBuilder.buildReportMenuStatus( 509 mAddress, message.getSource(), Constants.MENU_STATE_ACTIVATED)); 510 return true; 511 } 512 513 protected boolean handleVendorCommand(HdmiCecMessage message) { 514 mService.invokeVendorCommandListeners(mDeviceType, message.getSource(), 515 message.getParams(), false); 516 return true; 517 } 518 519 protected boolean handleVendorCommandWithId(HdmiCecMessage message) { 520 byte[] params = message.getParams(); 521 int vendorId = HdmiUtils.threeBytesToInt(params); 522 if (vendorId == mService.getVendorId()) { 523 mService.invokeVendorCommandListeners(mDeviceType, message.getSource(), params, true); 524 } else if (message.getDestination() != Constants.ADDR_BROADCAST && 525 message.getSource() != Constants.ADDR_UNREGISTERED) { 526 Slog.v(TAG, "Wrong direct vendor command. Replying with <Feature Abort>"); 527 mService.maySendFeatureAbortCommand(message, Constants.ABORT_UNRECOGNIZED_OPCODE); 528 } else { 529 Slog.v(TAG, "Wrong broadcast vendor command. Ignoring"); 530 } 531 return true; 532 } 533 534 protected boolean handleSetOsdName(HdmiCecMessage message) { 535 // The default behavior of <Set Osd Name> is doing nothing. 536 return true; 537 } 538 539 protected boolean handleRecordTvScreen(HdmiCecMessage message) { 540 // The default behavior of <Record TV Screen> is replying <Feature Abort> with 541 // "Cannot provide source". 542 mService.maySendFeatureAbortCommand(message, Constants.ABORT_CANNOT_PROVIDE_SOURCE); 543 return true; 544 } 545 546 protected boolean handleTimerClearedStatus(HdmiCecMessage message) { 547 return false; 548 } 549 550 protected boolean handleReportPowerStatus(HdmiCecMessage message) { 551 return false; 552 } 553 554 protected boolean handleTimerStatus(HdmiCecMessage message) { 555 return false; 556 } 557 558 protected boolean handleRecordStatus(HdmiCecMessage message) { 559 return false; 560 } 561 562 @ServiceThreadOnly 563 final void handleAddressAllocated(int logicalAddress, int reason) { 564 assertRunOnServiceThread(); 565 mAddress = mPreferredAddress = logicalAddress; 566 onAddressAllocated(logicalAddress, reason); 567 setPreferredAddress(logicalAddress); 568 } 569 570 int getType() { 571 return mDeviceType; 572 } 573 574 @ServiceThreadOnly 575 HdmiDeviceInfo getDeviceInfo() { 576 assertRunOnServiceThread(); 577 return mDeviceInfo; 578 } 579 580 @ServiceThreadOnly 581 void setDeviceInfo(HdmiDeviceInfo info) { 582 assertRunOnServiceThread(); 583 mDeviceInfo = info; 584 } 585 586 // Returns true if the logical address is same as the argument. 587 @ServiceThreadOnly 588 boolean isAddressOf(int addr) { 589 assertRunOnServiceThread(); 590 return addr == mAddress; 591 } 592 593 // Resets the logical address to unregistered(15), meaning the logical device is invalid. 594 @ServiceThreadOnly 595 void clearAddress() { 596 assertRunOnServiceThread(); 597 mAddress = Constants.ADDR_UNREGISTERED; 598 } 599 600 @ServiceThreadOnly 601 void addAndStartAction(final HdmiCecFeatureAction action) { 602 assertRunOnServiceThread(); 603 if (mService.isPowerStandbyOrTransient()) { 604 Slog.w(TAG, "Skip the action during Standby: " + action); 605 return; 606 } 607 mActions.add(action); 608 action.start(); 609 } 610 611 // See if we have an action of a given type in progress. 612 @ServiceThreadOnly 613 <T extends HdmiCecFeatureAction> boolean hasAction(final Class<T> clazz) { 614 assertRunOnServiceThread(); 615 for (HdmiCecFeatureAction action : mActions) { 616 if (action.getClass().equals(clazz)) { 617 return true; 618 } 619 } 620 return false; 621 } 622 623 // Returns all actions matched with given class type. 624 @ServiceThreadOnly 625 <T extends HdmiCecFeatureAction> List<T> getActions(final Class<T> clazz) { 626 assertRunOnServiceThread(); 627 List<T> actions = Collections.<T>emptyList(); 628 for (HdmiCecFeatureAction action : mActions) { 629 if (action.getClass().equals(clazz)) { 630 if (actions.isEmpty()) { 631 actions = new ArrayList<T>(); 632 } 633 actions.add((T) action); 634 } 635 } 636 return actions; 637 } 638 639 /** 640 * Remove the given {@link HdmiCecFeatureAction} object from the action queue. 641 * 642 * @param action {@link HdmiCecFeatureAction} to remove 643 */ 644 @ServiceThreadOnly 645 void removeAction(final HdmiCecFeatureAction action) { 646 assertRunOnServiceThread(); 647 action.finish(false); 648 mActions.remove(action); 649 checkIfPendingActionsCleared(); 650 } 651 652 // Remove all actions matched with the given Class type. 653 @ServiceThreadOnly 654 <T extends HdmiCecFeatureAction> void removeAction(final Class<T> clazz) { 655 assertRunOnServiceThread(); 656 removeActionExcept(clazz, null); 657 } 658 659 // Remove all actions matched with the given Class type besides |exception|. 660 @ServiceThreadOnly 661 <T extends HdmiCecFeatureAction> void removeActionExcept(final Class<T> clazz, 662 final HdmiCecFeatureAction exception) { 663 assertRunOnServiceThread(); 664 Iterator<HdmiCecFeatureAction> iter = mActions.iterator(); 665 while (iter.hasNext()) { 666 HdmiCecFeatureAction action = iter.next(); 667 if (action != exception && action.getClass().equals(clazz)) { 668 action.finish(false); 669 iter.remove(); 670 } 671 } 672 checkIfPendingActionsCleared(); 673 } 674 675 protected void checkIfPendingActionsCleared() { 676 if (mActions.isEmpty() && mPendingActionClearedCallback != null) { 677 PendingActionClearedCallback callback = mPendingActionClearedCallback; 678 // To prevent from calling the callback again during handling the callback itself. 679 mPendingActionClearedCallback = null; 680 callback.onCleared(this); 681 } 682 } 683 684 protected void assertRunOnServiceThread() { 685 if (Looper.myLooper() != mService.getServiceLooper()) { 686 throw new IllegalStateException("Should run on service thread."); 687 } 688 } 689 690 /** 691 * Called when a hot-plug event issued. 692 * 693 * @param portId id of port where a hot-plug event happened 694 * @param connected whether to connected or not on the event 695 */ 696 void onHotplug(int portId, boolean connected) { 697 } 698 699 final HdmiControlService getService() { 700 return mService; 701 } 702 703 @ServiceThreadOnly 704 final boolean isConnectedToArcPort(int path) { 705 assertRunOnServiceThread(); 706 return mService.isConnectedToArcPort(path); 707 } 708 709 ActiveSource getActiveSource() { 710 synchronized (mLock) { 711 return mActiveSource; 712 } 713 } 714 715 void setActiveSource(ActiveSource newActive) { 716 setActiveSource(newActive.logicalAddress, newActive.physicalAddress); 717 } 718 719 void setActiveSource(HdmiDeviceInfo info) { 720 setActiveSource(info.getLogicalAddress(), info.getPhysicalAddress()); 721 } 722 723 void setActiveSource(int logicalAddress, int physicalAddress) { 724 synchronized (mLock) { 725 mActiveSource.logicalAddress = logicalAddress; 726 mActiveSource.physicalAddress = physicalAddress; 727 } 728 mService.setLastInputForMhl(Constants.INVALID_PORT_ID); 729 } 730 731 int getActivePath() { 732 synchronized (mLock) { 733 return mActiveRoutingPath; 734 } 735 } 736 737 void setActivePath(int path) { 738 synchronized (mLock) { 739 mActiveRoutingPath = path; 740 } 741 mService.setActivePortId(pathToPortId(path)); 742 } 743 744 /** 745 * Returns the ID of the active HDMI port. The active port is the one that has the active 746 * routing path connected to it directly or indirectly under the device hierarchy. 747 */ 748 int getActivePortId() { 749 synchronized (mLock) { 750 return mService.pathToPortId(mActiveRoutingPath); 751 } 752 } 753 754 /** 755 * Update the active port. 756 * 757 * @param portId the new active port id 758 */ 759 void setActivePortId(int portId) { 760 // We update active routing path instead, since we get the active port id from 761 // the active routing path. 762 setActivePath(mService.portIdToPath(portId)); 763 } 764 765 @ServiceThreadOnly 766 HdmiCecMessageCache getCecMessageCache() { 767 assertRunOnServiceThread(); 768 return mCecMessageCache; 769 } 770 771 @ServiceThreadOnly 772 int pathToPortId(int newPath) { 773 assertRunOnServiceThread(); 774 return mService.pathToPortId(newPath); 775 } 776 777 /** 778 * Called when the system goes to standby mode. 779 * 780 * @param initiatedByCec true if this power sequence is initiated 781 * by the reception the CEC messages like <Standby> 782 */ 783 protected void onStandby(boolean initiatedByCec) {} 784 785 /** 786 * Disable device. {@code callback} is used to get notified when all pending 787 * actions are completed or timeout is issued. 788 * 789 * @param initiatedByCec true if this sequence is initiated 790 * by the reception the CEC messages like <Standby> 791 * @param origialCallback callback interface to get notified when all pending actions are 792 * cleared 793 */ 794 protected void disableDevice(boolean initiatedByCec, 795 final PendingActionClearedCallback origialCallback) { 796 mPendingActionClearedCallback = new PendingActionClearedCallback() { 797 @Override 798 public void onCleared(HdmiCecLocalDevice device) { 799 mHandler.removeMessages(MSG_DISABLE_DEVICE_TIMEOUT); 800 origialCallback.onCleared(device); 801 } 802 }; 803 mHandler.sendMessageDelayed(Message.obtain(mHandler, MSG_DISABLE_DEVICE_TIMEOUT), 804 DEVICE_CLEANUP_TIMEOUT); 805 } 806 807 @ServiceThreadOnly 808 private void handleDisableDeviceTimeout() { 809 assertRunOnServiceThread(); 810 811 // If all actions are not cleared in DEVICE_CLEANUP_TIMEOUT, enforce to finish them. 812 // onCleard will be called at the last action's finish method. 813 Iterator<HdmiCecFeatureAction> iter = mActions.iterator(); 814 while (iter.hasNext()) { 815 HdmiCecFeatureAction action = iter.next(); 816 action.finish(false); 817 iter.remove(); 818 } 819 } 820 821 /** 822 * Send a key event to other device. 823 * 824 * @param keyCode key code defined in {@link android.view.KeyEvent} 825 * @param isPressed {@code true} for key down event 826 */ 827 protected void sendKeyEvent(int keyCode, boolean isPressed) { 828 Slog.w(TAG, "sendKeyEvent not implemented"); 829 } 830 831 void sendUserControlPressedAndReleased(int targetAddress, int cecKeycode) { 832 mService.sendCecCommand(HdmiCecMessageBuilder.buildUserControlPressed( 833 mAddress, targetAddress, cecKeycode)); 834 mService.sendCecCommand(HdmiCecMessageBuilder.buildUserControlReleased( 835 mAddress, targetAddress)); 836 } 837 838 /** 839 * Dump internal status of HdmiCecLocalDevice object. 840 */ 841 protected void dump(final IndentingPrintWriter pw) { 842 pw.println("mDeviceType: " + mDeviceType); 843 pw.println("mAddress: " + mAddress); 844 pw.println("mPreferredAddress: " + mPreferredAddress); 845 pw.println("mDeviceInfo: " + mDeviceInfo); 846 pw.println("mActiveSource: " + mActiveSource); 847 pw.println(String.format("mActiveRoutingPath: 0x%04x", mActiveRoutingPath)); 848 } 849} 850