HdmiCecLocalDevice.java revision af2acf0447aff34450cde2bcfb35dff9cf631729
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.HdmiCecDeviceInfo; 20import android.os.Handler; 21import android.os.Looper; 22import android.os.Message; 23import android.os.SystemProperties; 24import android.util.Slog; 25 26import com.android.internal.annotations.GuardedBy; 27import com.android.server.hdmi.HdmiAnnotations.ServiceThreadOnly; 28 29import java.util.ArrayList; 30import java.util.Iterator; 31import java.util.LinkedList; 32import java.util.List; 33 34/** 35 * Class that models a logical CEC device hosted in this system. Handles initialization, 36 * CEC commands that call for actions customized per device type. 37 */ 38abstract class HdmiCecLocalDevice { 39 private static final String TAG = "HdmiCecLocalDevice"; 40 41 private static final int MSG_DISABLE_DEVICE_TIMEOUT = 1; 42 // Timeout in millisecond for device clean up (5s). 43 // Normal actions timeout is 2s but some of them would have several sequence of timeout. 44 private static final int DEVICE_CLEANUP_TIMEOUT = 5000; 45 46 protected final HdmiControlService mService; 47 protected final int mDeviceType; 48 protected int mAddress; 49 protected int mPreferredAddress; 50 protected HdmiCecDeviceInfo mDeviceInfo; 51 52 // Logical address of the active source. 53 @GuardedBy("mLock") 54 private int mActiveSource; 55 56 // Active routing path. Physical address of the active source but not all the time, such as 57 // when the new active source does not claim itself to be one. Note that we don't keep 58 // the active port id (or active input) since it can be gotten by {@link #pathToPortId(int)}. 59 @GuardedBy("mLock") 60 private int mActiveRoutingPath; 61 62 protected final HdmiCecMessageCache mCecMessageCache = new HdmiCecMessageCache(); 63 protected final Object mLock; 64 65 // A collection of FeatureAction. 66 // Note that access to this collection should happen in service thread. 67 private final LinkedList<FeatureAction> mActions = new LinkedList<>(); 68 69 private final Handler mHandler = new Handler () { 70 @Override 71 public void handleMessage(Message msg) { 72 switch (msg.what) { 73 case MSG_DISABLE_DEVICE_TIMEOUT: 74 handleDisableDeviceTimeout(); 75 break; 76 } 77 } 78 }; 79 80 /** 81 * A callback interface to get notified when all pending action is cleared. 82 * It can be called when timeout happened. 83 */ 84 interface PendingActionClearedCallback { 85 void onCleared(HdmiCecLocalDevice device); 86 } 87 88 protected PendingActionClearedCallback mPendingActionClearedCallback; 89 90 protected HdmiCecLocalDevice(HdmiControlService service, int deviceType) { 91 mService = service; 92 mDeviceType = deviceType; 93 mAddress = Constants.ADDR_UNREGISTERED; 94 mLock = service.getServiceLock(); 95 } 96 97 // Factory method that returns HdmiCecLocalDevice of corresponding type. 98 static HdmiCecLocalDevice create(HdmiControlService service, int deviceType) { 99 switch (deviceType) { 100 case HdmiCecDeviceInfo.DEVICE_TV: 101 return new HdmiCecLocalDeviceTv(service); 102 case HdmiCecDeviceInfo.DEVICE_PLAYBACK: 103 return new HdmiCecLocalDevicePlayback(service); 104 default: 105 return null; 106 } 107 } 108 109 @ServiceThreadOnly 110 void init() { 111 assertRunOnServiceThread(); 112 mPreferredAddress = getPreferredAddress(); 113 } 114 115 /** 116 * Called once a logical address of the local device is allocated. 117 */ 118 protected abstract void onAddressAllocated(int logicalAddress, boolean fromBootup); 119 120 /** 121 * Get the preferred logical address from system properties. 122 */ 123 protected abstract int getPreferredAddress(); 124 125 /** 126 * Set the preferred logical address to system properties. 127 */ 128 protected abstract void setPreferredAddress(int addr); 129 130 /** 131 * Dispatch incoming message. 132 * 133 * @param message incoming message 134 * @return true if consumed a message; otherwise, return false. 135 */ 136 @ServiceThreadOnly 137 final boolean dispatchMessage(HdmiCecMessage message) { 138 assertRunOnServiceThread(); 139 int dest = message.getDestination(); 140 if (dest != mAddress && dest != Constants.ADDR_BROADCAST) { 141 return false; 142 } 143 // Cache incoming message. Note that it caches only white-listed one. 144 mCecMessageCache.cacheMessage(message); 145 return onMessage(message); 146 } 147 148 @ServiceThreadOnly 149 protected final boolean onMessage(HdmiCecMessage message) { 150 assertRunOnServiceThread(); 151 if (dispatchMessageToAction(message)) { 152 return true; 153 } 154 switch (message.getOpcode()) { 155 case Constants.MESSAGE_ACTIVE_SOURCE: 156 return handleActiveSource(message); 157 case Constants.MESSAGE_INACTIVE_SOURCE: 158 return handleInactiveSource(message); 159 case Constants.MESSAGE_REQUEST_ACTIVE_SOURCE: 160 return handleRequestActiveSource(message); 161 case Constants.MESSAGE_GET_MENU_LANGUAGE: 162 return handleGetMenuLanguage(message); 163 case Constants.MESSAGE_GIVE_PHYSICAL_ADDRESS: 164 return handleGivePhysicalAddress(); 165 case Constants.MESSAGE_GIVE_OSD_NAME: 166 return handleGiveOsdName(message); 167 case Constants.MESSAGE_GIVE_DEVICE_VENDOR_ID: 168 return handleGiveDeviceVendorId(); 169 case Constants.MESSAGE_GET_CEC_VERSION: 170 return handleGetCecVersion(message); 171 case Constants.MESSAGE_REPORT_PHYSICAL_ADDRESS: 172 return handleReportPhysicalAddress(message); 173 case Constants.MESSAGE_ROUTING_CHANGE: 174 return handleRoutingChange(message); 175 case Constants.MESSAGE_INITIATE_ARC: 176 return handleInitiateArc(message); 177 case Constants.MESSAGE_TERMINATE_ARC: 178 return handleTerminateArc(message); 179 case Constants.MESSAGE_SET_SYSTEM_AUDIO_MODE: 180 return handleSetSystemAudioMode(message); 181 case Constants.MESSAGE_SYSTEM_AUDIO_MODE_STATUS: 182 return handleSystemAudioModeStatus(message); 183 case Constants.MESSAGE_REPORT_AUDIO_STATUS: 184 return handleReportAudioStatus(message); 185 case Constants.MESSAGE_STANDBY: 186 return handleStandby(message); 187 case Constants.MESSAGE_TEXT_VIEW_ON: 188 return handleTextViewOn(message); 189 case Constants.MESSAGE_IMAGE_VIEW_ON: 190 return handleImageViewOn(message); 191 case Constants.MESSAGE_USER_CONTROL_PRESSED: 192 return handleUserControlPressed(message); 193 case Constants.MESSAGE_SET_STREAM_PATH: 194 return handleSetStreamPath(message); 195 case Constants.MESSAGE_GIVE_DEVICE_POWER_STATUS: 196 return handleGiveDevicePowerStatus(message); 197 case Constants.MESSAGE_VENDOR_COMMAND: 198 return handleVendorCommand(message); 199 case Constants.MESSAGE_VENDOR_COMMAND_WITH_ID: 200 return handleVendorCommandWithId(message); 201 case Constants.MESSAGE_SET_OSD_NAME: 202 return handleSetOsdName(message); 203 default: 204 return false; 205 } 206 } 207 208 @ServiceThreadOnly 209 private boolean dispatchMessageToAction(HdmiCecMessage message) { 210 assertRunOnServiceThread(); 211 for (FeatureAction action : mActions) { 212 if (action.processCommand(message)) { 213 return true; 214 } 215 } 216 return false; 217 } 218 219 @ServiceThreadOnly 220 protected boolean handleGivePhysicalAddress() { 221 assertRunOnServiceThread(); 222 223 int physicalAddress = mService.getPhysicalAddress(); 224 HdmiCecMessage cecMessage = HdmiCecMessageBuilder.buildReportPhysicalAddressCommand( 225 mAddress, physicalAddress, mDeviceType); 226 mService.sendCecCommand(cecMessage); 227 return true; 228 } 229 230 @ServiceThreadOnly 231 protected boolean handleGiveDeviceVendorId() { 232 assertRunOnServiceThread(); 233 int vendorId = mService.getVendorId(); 234 HdmiCecMessage cecMessage = HdmiCecMessageBuilder.buildDeviceVendorIdCommand( 235 mAddress, vendorId); 236 mService.sendCecCommand(cecMessage); 237 return true; 238 } 239 240 @ServiceThreadOnly 241 protected boolean handleGetCecVersion(HdmiCecMessage message) { 242 assertRunOnServiceThread(); 243 int version = mService.getCecVersion(); 244 HdmiCecMessage cecMessage = HdmiCecMessageBuilder.buildCecVersion(message.getDestination(), 245 message.getSource(), version); 246 mService.sendCecCommand(cecMessage); 247 return true; 248 } 249 250 @ServiceThreadOnly 251 protected boolean handleActiveSource(HdmiCecMessage message) { 252 return false; 253 } 254 255 @ServiceThreadOnly 256 protected boolean handleInactiveSource(HdmiCecMessage message) { 257 return false; 258 } 259 260 @ServiceThreadOnly 261 protected boolean handleRequestActiveSource(HdmiCecMessage message) { 262 return false; 263 } 264 265 @ServiceThreadOnly 266 protected boolean handleGetMenuLanguage(HdmiCecMessage message) { 267 assertRunOnServiceThread(); 268 Slog.w(TAG, "Only TV can handle <Get Menu Language>:" + message.toString()); 269 mService.sendCecCommand( 270 HdmiCecMessageBuilder.buildFeatureAbortCommand(mAddress, 271 message.getSource(), Constants.MESSAGE_GET_MENU_LANGUAGE, 272 Constants.ABORT_UNRECOGNIZED_MODE)); 273 return true; 274 } 275 276 @ServiceThreadOnly 277 protected boolean handleGiveOsdName(HdmiCecMessage message) { 278 assertRunOnServiceThread(); 279 // Note that since this method is called after logical address allocation is done, 280 // mDeviceInfo should not be null. 281 HdmiCecMessage cecMessage = HdmiCecMessageBuilder.buildSetOsdNameCommand( 282 mAddress, message.getSource(), mDeviceInfo.getDisplayName()); 283 if (cecMessage != null) { 284 mService.sendCecCommand(cecMessage); 285 } else { 286 Slog.w(TAG, "Failed to build <Get Osd Name>:" + mDeviceInfo.getDisplayName()); 287 } 288 return true; 289 } 290 291 protected boolean handleRoutingChange(HdmiCecMessage message) { 292 return false; 293 } 294 295 protected boolean handleReportPhysicalAddress(HdmiCecMessage message) { 296 return false; 297 } 298 299 protected boolean handleSystemAudioModeStatus(HdmiCecMessage message) { 300 return false; 301 } 302 303 protected boolean handleSetSystemAudioMode(HdmiCecMessage message) { 304 return false; 305 } 306 307 protected boolean handleTerminateArc(HdmiCecMessage message) { 308 return false; 309 } 310 311 protected boolean handleInitiateArc(HdmiCecMessage message) { 312 return false; 313 } 314 315 protected boolean handleReportAudioStatus(HdmiCecMessage message) { 316 return false; 317 } 318 319 @ServiceThreadOnly 320 protected boolean handleStandby(HdmiCecMessage message) { 321 assertRunOnServiceThread(); 322 // Seq #12 323 if (mService.isControlEnabled() && !mService.isProhibitMode() 324 && mService.isPowerOnOrTransient()) { 325 mService.standby(); 326 return true; 327 } 328 return false; 329 } 330 331 @ServiceThreadOnly 332 protected boolean handleUserControlPressed(HdmiCecMessage message) { 333 assertRunOnServiceThread(); 334 if (mService.isPowerOnOrTransient() && isPowerOffOrToggleCommand(message)) { 335 mService.standby(); 336 return true; 337 } else if (mService.isPowerStandbyOrTransient() && isPowerOnOrToggleCommand(message)) { 338 mService.wakeUp(); 339 return true; 340 } 341 return false; 342 } 343 344 private static boolean isPowerOnOrToggleCommand(HdmiCecMessage message) { 345 byte[] params = message.getParams(); 346 return message.getOpcode() == Constants.MESSAGE_USER_CONTROL_PRESSED 347 && (params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER 348 || params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER_ON_FUNCTION 349 || params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER_TOGGLE_FUNCTION); 350 } 351 352 private static boolean isPowerOffOrToggleCommand(HdmiCecMessage message) { 353 byte[] params = message.getParams(); 354 return message.getOpcode() == Constants.MESSAGE_USER_CONTROL_PRESSED 355 && (params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER 356 || params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER_OFF_FUNCTION 357 || params[0] == HdmiCecKeycode.CEC_KEYCODE_POWER_TOGGLE_FUNCTION); 358 } 359 360 protected boolean handleTextViewOn(HdmiCecMessage message) { 361 return false; 362 } 363 364 protected boolean handleImageViewOn(HdmiCecMessage message) { 365 return false; 366 } 367 368 protected boolean handleSetStreamPath(HdmiCecMessage message) { 369 return false; 370 } 371 372 protected boolean handleGiveDevicePowerStatus(HdmiCecMessage message) { 373 mService.sendCecCommand(HdmiCecMessageBuilder.buildReportPowerStatus( 374 mAddress, message.getSource(), mService.getPowerStatus())); 375 return true; 376 } 377 378 protected boolean handleVendorCommand(HdmiCecMessage message) { 379 mService.invokeVendorCommandListeners(mDeviceType, message.getSource(), 380 message.getParams(), false); 381 return true; 382 } 383 384 protected boolean handleVendorCommandWithId(HdmiCecMessage message) { 385 byte[] params = message.getParams(); 386 int vendorId = HdmiUtils.threeBytesToInt(params); 387 if (vendorId == mService.getVendorId()) { 388 mService.invokeVendorCommandListeners(mDeviceType, message.getSource(), params, true); 389 } else if (message.getDestination() != Constants.ADDR_BROADCAST && 390 message.getSource() != Constants.ADDR_UNREGISTERED) { 391 Slog.v(TAG, "Wrong direct vendor command. Replying with <Feature Abort>"); 392 mService.sendCecCommand(HdmiCecMessageBuilder.buildFeatureAbortCommand(mAddress, 393 message.getSource(), Constants.MESSAGE_VENDOR_COMMAND_WITH_ID, 394 Constants.ABORT_UNRECOGNIZED_MODE)); 395 } else { 396 Slog.v(TAG, "Wrong broadcast vendor command. Ignoring"); 397 } 398 return true; 399 } 400 401 protected boolean handleSetOsdName(HdmiCecMessage message) { 402 // The default behavior of <Set Osd Name> is doing nothing. 403 return true; 404 } 405 406 @ServiceThreadOnly 407 final void handleAddressAllocated(int logicalAddress, boolean fromBootup) { 408 assertRunOnServiceThread(); 409 mAddress = mPreferredAddress = logicalAddress; 410 onAddressAllocated(logicalAddress, fromBootup); 411 setPreferredAddress(logicalAddress); 412 } 413 414 @ServiceThreadOnly 415 HdmiCecDeviceInfo getDeviceInfo() { 416 assertRunOnServiceThread(); 417 return mDeviceInfo; 418 } 419 420 @ServiceThreadOnly 421 void setDeviceInfo(HdmiCecDeviceInfo info) { 422 assertRunOnServiceThread(); 423 mDeviceInfo = info; 424 } 425 426 // Returns true if the logical address is same as the argument. 427 @ServiceThreadOnly 428 boolean isAddressOf(int addr) { 429 assertRunOnServiceThread(); 430 return addr == mAddress; 431 } 432 433 // Resets the logical address to unregistered(15), meaning the logical device is invalid. 434 @ServiceThreadOnly 435 void clearAddress() { 436 assertRunOnServiceThread(); 437 mAddress = Constants.ADDR_UNREGISTERED; 438 } 439 440 @ServiceThreadOnly 441 void addAndStartAction(final FeatureAction action) { 442 assertRunOnServiceThread(); 443 if (mService.isPowerStandbyOrTransient()) { 444 Slog.w(TAG, "Skip the action during Standby: " + action); 445 return; 446 } 447 mActions.add(action); 448 action.start(); 449 } 450 451 // See if we have an action of a given type in progress. 452 @ServiceThreadOnly 453 <T extends FeatureAction> boolean hasAction(final Class<T> clazz) { 454 assertRunOnServiceThread(); 455 for (FeatureAction action : mActions) { 456 if (action.getClass().equals(clazz)) { 457 return true; 458 } 459 } 460 return false; 461 } 462 463 // Returns all actions matched with given class type. 464 @ServiceThreadOnly 465 <T extends FeatureAction> List<T> getActions(final Class<T> clazz) { 466 assertRunOnServiceThread(); 467 ArrayList<T> actions = new ArrayList<>(); 468 for (FeatureAction action : mActions) { 469 if (action.getClass().equals(clazz)) { 470 actions.add((T) action); 471 } 472 } 473 return actions; 474 } 475 476 /** 477 * Remove the given {@link FeatureAction} object from the action queue. 478 * 479 * @param action {@link FeatureAction} to remove 480 */ 481 @ServiceThreadOnly 482 void removeAction(final FeatureAction action) { 483 assertRunOnServiceThread(); 484 action.finish(false); 485 mActions.remove(action); 486 checkIfPendingActionsCleared(); 487 } 488 489 // Remove all actions matched with the given Class type. 490 @ServiceThreadOnly 491 <T extends FeatureAction> void removeAction(final Class<T> clazz) { 492 assertRunOnServiceThread(); 493 removeActionExcept(clazz, null); 494 } 495 496 // Remove all actions matched with the given Class type besides |exception|. 497 @ServiceThreadOnly 498 <T extends FeatureAction> void removeActionExcept(final Class<T> clazz, 499 final FeatureAction exception) { 500 assertRunOnServiceThread(); 501 Iterator<FeatureAction> iter = mActions.iterator(); 502 while (iter.hasNext()) { 503 FeatureAction action = iter.next(); 504 if (action != exception && action.getClass().equals(clazz)) { 505 action.finish(false); 506 iter.remove(); 507 } 508 } 509 checkIfPendingActionsCleared(); 510 } 511 512 protected void checkIfPendingActionsCleared() { 513 if (mActions.isEmpty() && mPendingActionClearedCallback != null) { 514 mPendingActionClearedCallback.onCleared(this); 515 } 516 } 517 518 protected void assertRunOnServiceThread() { 519 if (Looper.myLooper() != mService.getServiceLooper()) { 520 throw new IllegalStateException("Should run on service thread."); 521 } 522 } 523 524 /** 525 * Called when a hot-plug event issued. 526 * 527 * @param portId id of port where a hot-plug event happened 528 * @param connected whether to connected or not on the event 529 */ 530 void onHotplug(int portId, boolean connected) { 531 } 532 533 final HdmiControlService getService() { 534 return mService; 535 } 536 537 @ServiceThreadOnly 538 final boolean isConnectedToArcPort(int path) { 539 assertRunOnServiceThread(); 540 return mService.isConnectedToArcPort(path); 541 } 542 543 int getActiveSource() { 544 synchronized (mLock) { 545 return mActiveSource; 546 } 547 } 548 549 void setActiveSource(int source) { 550 synchronized (mLock) { 551 mActiveSource = source; 552 } 553 } 554 555 int getActivePath() { 556 synchronized (mLock) { 557 return mActiveRoutingPath; 558 } 559 } 560 561 void setActivePath(int path) { 562 synchronized (mLock) { 563 mActiveRoutingPath = path; 564 } 565 } 566 567 /** 568 * Returns the ID of the active HDMI port. The active port is the one that has the active 569 * routing path connected to it directly or indirectly under the device hierarchy. 570 */ 571 int getActivePortId() { 572 synchronized (mLock) { 573 return mService.pathToPortId(mActiveRoutingPath); 574 } 575 } 576 577 /** 578 * Update the active port. 579 * 580 * @param portId the new active port id 581 */ 582 void setActivePortId(int portId) { 583 synchronized (mLock) { 584 // We update active routing path instead, since we get the active port id from 585 // the active routing path. 586 mActiveRoutingPath = mService.portIdToPath(portId); 587 } 588 } 589 590 void updateActiveDevice(int logicalAddress, int physicalAddress) { 591 synchronized (mLock) { 592 mActiveSource = logicalAddress; 593 mActiveRoutingPath = physicalAddress; 594 } 595 } 596 597 @ServiceThreadOnly 598 HdmiCecMessageCache getCecMessageCache() { 599 assertRunOnServiceThread(); 600 return mCecMessageCache; 601 } 602 603 @ServiceThreadOnly 604 int pathToPortId(int newPath) { 605 assertRunOnServiceThread(); 606 return mService.pathToPortId(newPath); 607 } 608 609 /** 610 * Called when the system goes to standby mode. 611 * 612 * @param initiatedByCec true if this power sequence is initiated 613 * by the reception the CEC messages like <Standby> 614 */ 615 protected void onStandby(boolean initiatedByCec) {} 616 617 /** 618 * Disable device. {@code callback} is used to get notified when all pending 619 * actions are completed or timeout is issued. 620 * 621 * @param initiatedByCec true if this sequence is initiated 622 * by the reception the CEC messages like <Standby> 623 * @param origialCallback callback interface to get notified when all pending actions are 624 * cleared 625 */ 626 protected void disableDevice(boolean initiatedByCec, 627 final PendingActionClearedCallback origialCallback) { 628 mPendingActionClearedCallback = new PendingActionClearedCallback() { 629 @Override 630 public void onCleared(HdmiCecLocalDevice device) { 631 mHandler.removeMessages(MSG_DISABLE_DEVICE_TIMEOUT); 632 origialCallback.onCleared(device); 633 } 634 }; 635 mHandler.sendMessageDelayed(Message.obtain(mHandler, MSG_DISABLE_DEVICE_TIMEOUT), 636 DEVICE_CLEANUP_TIMEOUT); 637 } 638 639 @ServiceThreadOnly 640 private void handleDisableDeviceTimeout() { 641 assertRunOnServiceThread(); 642 643 // If all actions are not cleared in DEVICE_CLEANUP_TIMEOUT, enforce to finish them. 644 // onCleard will be called at the last action's finish method. 645 Iterator<FeatureAction> iter = mActions.iterator(); 646 while (iter.hasNext()) { 647 FeatureAction action = iter.next(); 648 action.finish(false); 649 iter.remove(); 650 } 651 } 652 653 /** 654 * Send a key event to other device. 655 * 656 * @param keyCode key code defined in {@link android.view.KeyEvent} 657 * @param isPressed {@code true} for key down event 658 */ 659 protected void sendKeyEvent(int keyCode, boolean isPressed) { 660 Slog.w(TAG, "sendKeyEvent not implemented"); 661 } 662} 663