HdmiCecLocalDeviceTv.java revision 184b124ec22a796327642e3546d366179e693f07
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 static android.hardware.hdmi.HdmiControlManager.CLEAR_TIMER_STATUS_CEC_DISABLE; 20import static android.hardware.hdmi.HdmiControlManager.CLEAR_TIMER_STATUS_CHECK_RECORDER_CONNECTION; 21import static android.hardware.hdmi.HdmiControlManager.CLEAR_TIMER_STATUS_FAIL_TO_CLEAR_SELECTED_SOURCE; 22import static android.hardware.hdmi.HdmiControlManager.ONE_TOUCH_RECORD_CEC_DISABLED; 23import static android.hardware.hdmi.HdmiControlManager.ONE_TOUCH_RECORD_CHECK_RECORDER_CONNECTION; 24import static android.hardware.hdmi.HdmiControlManager.ONE_TOUCH_RECORD_FAIL_TO_RECORD_DISPLAYED_SCREEN; 25import static android.hardware.hdmi.HdmiControlManager.OSD_MESSAGE_ARC_CONNECTED_INVALID_PORT; 26import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_RESULT_EXTRA_CEC_DISABLED; 27import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_RESULT_EXTRA_CHECK_RECORDER_CONNECTION; 28import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_RESULT_EXTRA_FAIL_TO_RECORD_SELECTED_SOURCE; 29import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_TYPE_ANALOGUE; 30import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_TYPE_DIGITAL; 31import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_TYPE_EXTERNAL; 32 33import android.hardware.hdmi.HdmiControlManager; 34import android.hardware.hdmi.HdmiDeviceInfo; 35import android.hardware.hdmi.HdmiRecordSources; 36import android.hardware.hdmi.HdmiTimerRecordSources; 37import android.hardware.hdmi.IHdmiControlCallback; 38import android.media.AudioManager; 39import android.media.AudioSystem; 40import android.os.RemoteException; 41import android.os.SystemProperties; 42import android.provider.Settings.Global; 43import android.util.ArraySet; 44import android.util.Slog; 45import android.util.SparseArray; 46 47import com.android.internal.annotations.GuardedBy; 48import com.android.internal.util.IndentingPrintWriter; 49import com.android.server.hdmi.DeviceDiscoveryAction.DeviceDiscoveryCallback; 50import com.android.server.hdmi.HdmiAnnotations.ServiceThreadOnly; 51import com.android.server.hdmi.HdmiControlService.SendMessageCallback; 52 53import java.io.UnsupportedEncodingException; 54import java.util.ArrayList; 55import java.util.Arrays; 56import java.util.Collection; 57import java.util.Collections; 58import java.util.Iterator; 59import java.util.List; 60 61/** 62 * Represent a logical device of type TV residing in Android system. 63 */ 64final class HdmiCecLocalDeviceTv extends HdmiCecLocalDevice { 65 private static final String TAG = "HdmiCecLocalDeviceTv"; 66 67 // Whether ARC is available or not. "true" means that ARC is established between TV and 68 // AVR as audio receiver. 69 @ServiceThreadOnly 70 private boolean mArcEstablished = false; 71 72 // Whether ARC feature is enabled or not. The default value is true. 73 // TODO: once adding system setting for it, read the value to it. 74 private boolean mArcFeatureEnabled = true; 75 76 // Whether System audio mode is activated or not. 77 // This becomes true only when all system audio sequences are finished. 78 @GuardedBy("mLock") 79 private boolean mSystemAudioActivated = false; 80 81 // The previous port id (input) before switching to the new one. This is remembered in order to 82 // be able to switch to it upon receiving <Inactive Source> from currently active source. 83 // This remains valid only when the active source was switched via one touch play operation 84 // (either by TV or source device). Manual port switching invalidates this value to 85 // Constants.PORT_INVALID, for which case <Inactive Source> does not do anything. 86 @GuardedBy("mLock") 87 private int mPrevPortId; 88 89 @GuardedBy("mLock") 90 private int mSystemAudioVolume = Constants.UNKNOWN_VOLUME; 91 92 @GuardedBy("mLock") 93 private boolean mSystemAudioMute = false; 94 95 // Copy of mDeviceInfos to guarantee thread-safety. 96 @GuardedBy("mLock") 97 private List<HdmiDeviceInfo> mSafeAllDeviceInfos = Collections.emptyList(); 98 // All external cec input(source) devices. Does not include system audio device. 99 @GuardedBy("mLock") 100 private List<HdmiDeviceInfo> mSafeExternalInputs = Collections.emptyList(); 101 102 // Map-like container of all cec devices including local ones. 103 // device id is used as key of container. 104 // This is not thread-safe. For external purpose use mSafeDeviceInfos. 105 private final SparseArray<HdmiDeviceInfo> mDeviceInfos = new SparseArray<>(); 106 107 // If true, TV going to standby mode puts other devices also to standby. 108 private boolean mAutoDeviceOff; 109 110 // If true, TV wakes itself up when receiving <Text/Image View On>. 111 private boolean mAutoWakeup; 112 113 private final HdmiCecStandbyModeHandler mStandbyHandler; 114 115 // If true, do not do routing control/send active source for internal source. 116 // Set to true when the device was woken up by <Text/Image View On>. 117 private boolean mSkipRoutingControl; 118 119 // Set of physical addresses of CEC switches on the CEC bus. Managed independently from 120 // other CEC devices since they might not have logical address. 121 private final ArraySet<Integer> mCecSwitches = new ArraySet<Integer>(); 122 123 HdmiCecLocalDeviceTv(HdmiControlService service) { 124 super(service, HdmiDeviceInfo.DEVICE_TV); 125 mPrevPortId = Constants.INVALID_PORT_ID; 126 mAutoDeviceOff = mService.readBooleanSetting(Global.HDMI_CONTROL_AUTO_DEVICE_OFF_ENABLED, 127 true); 128 mAutoWakeup = mService.readBooleanSetting(Global.HDMI_CONTROL_AUTO_WAKEUP_ENABLED, true); 129 mStandbyHandler = new HdmiCecStandbyModeHandler(service, this); 130 } 131 132 @Override 133 @ServiceThreadOnly 134 protected void onAddressAllocated(int logicalAddress, int reason) { 135 assertRunOnServiceThread(); 136 mService.sendCecCommand(HdmiCecMessageBuilder.buildReportPhysicalAddressCommand( 137 mAddress, mService.getPhysicalAddress(), mDeviceType)); 138 mService.sendCecCommand(HdmiCecMessageBuilder.buildDeviceVendorIdCommand( 139 mAddress, mService.getVendorId())); 140 mCecSwitches.add(mService.getPhysicalAddress()); // TV is a CEC switch too. 141 mSkipRoutingControl = (reason == HdmiControlService.INITIATED_BY_WAKE_UP_MESSAGE); 142 launchRoutingControl(reason != HdmiControlService.INITIATED_BY_ENABLE_CEC && 143 reason != HdmiControlService.INITIATED_BY_BOOT_UP); 144 launchDeviceDiscovery(); 145 } 146 147 @Override 148 @ServiceThreadOnly 149 protected int getPreferredAddress() { 150 assertRunOnServiceThread(); 151 return SystemProperties.getInt(Constants.PROPERTY_PREFERRED_ADDRESS_TV, 152 Constants.ADDR_UNREGISTERED); 153 } 154 155 @Override 156 @ServiceThreadOnly 157 protected void setPreferredAddress(int addr) { 158 assertRunOnServiceThread(); 159 SystemProperties.set(Constants.PROPERTY_PREFERRED_ADDRESS_TV, String.valueOf(addr)); 160 } 161 162 @Override 163 @ServiceThreadOnly 164 boolean dispatchMessage(HdmiCecMessage message) { 165 assertRunOnServiceThread(); 166 if (mService.isPowerStandby() && mStandbyHandler.handleCommand(message)) { 167 return true; 168 } 169 return super.onMessage(message); 170 } 171 172 /** 173 * Performs the action 'device select', or 'one touch play' initiated by TV. 174 * 175 * @param id id of HDMI device to select 176 * @param callback callback object to report the result with 177 */ 178 @ServiceThreadOnly 179 void deviceSelect(int id, IHdmiControlCallback callback) { 180 assertRunOnServiceThread(); 181 HdmiDeviceInfo targetDevice = mDeviceInfos.get(id); 182 if (targetDevice == null) { 183 invokeCallback(callback, HdmiControlManager.RESULT_TARGET_NOT_AVAILABLE); 184 return; 185 } 186 int targetAddress = targetDevice.getLogicalAddress(); 187 ActiveSource active = getActiveSource(); 188 if (active.isValid() && targetAddress == active.logicalAddress) { 189 invokeCallback(callback, HdmiControlManager.RESULT_SUCCESS); 190 return; 191 } 192 if (targetAddress == Constants.ADDR_INTERNAL) { 193 handleSelectInternalSource(); 194 // Switching to internal source is always successful even when CEC control is disabled. 195 setActiveSource(targetAddress, mService.getPhysicalAddress()); 196 setActivePath(mService.getPhysicalAddress()); 197 invokeCallback(callback, HdmiControlManager.RESULT_SUCCESS); 198 return; 199 } 200 if (!mService.isControlEnabled()) { 201 setActiveSource(targetDevice); 202 invokeCallback(callback, HdmiControlManager.RESULT_INCORRECT_MODE); 203 return; 204 } 205 removeAction(DeviceSelectAction.class); 206 addAndStartAction(new DeviceSelectAction(this, targetDevice, callback)); 207 } 208 209 @ServiceThreadOnly 210 private void handleSelectInternalSource() { 211 assertRunOnServiceThread(); 212 // Seq #18 213 if (mService.isControlEnabled() && mActiveSource.logicalAddress != mAddress) { 214 updateActiveSource(mAddress, mService.getPhysicalAddress()); 215 if (mSkipRoutingControl) { 216 mSkipRoutingControl = false; 217 return; 218 } 219 HdmiCecMessage activeSource = HdmiCecMessageBuilder.buildActiveSource( 220 mAddress, mService.getPhysicalAddress()); 221 mService.sendCecCommand(activeSource); 222 } 223 } 224 225 @ServiceThreadOnly 226 void updateActiveSource(int logicalAddress, int physicalAddress) { 227 assertRunOnServiceThread(); 228 updateActiveSource(ActiveSource.of(logicalAddress, physicalAddress)); 229 } 230 231 @ServiceThreadOnly 232 void updateActiveSource(ActiveSource newActive) { 233 assertRunOnServiceThread(); 234 // Seq #14 235 if (mActiveSource.equals(newActive)) { 236 return; 237 } 238 setActiveSource(newActive); 239 int logicalAddress = newActive.logicalAddress; 240 if (getCecDeviceInfo(logicalAddress) != null && logicalAddress != mAddress) { 241 if (mService.pathToPortId(newActive.physicalAddress) == getActivePortId()) { 242 setPrevPortId(getActivePortId()); 243 } 244 // TODO: Show the OSD banner related to the new active source device. 245 } else { 246 // TODO: If displayed, remove the OSD banner related to the previous 247 // active source device. 248 } 249 } 250 251 int getPortId(int physicalAddress) { 252 return mService.pathToPortId(physicalAddress); 253 } 254 255 /** 256 * Returns the previous port id kept to handle input switching on <Inactive Source>. 257 */ 258 int getPrevPortId() { 259 synchronized (mLock) { 260 return mPrevPortId; 261 } 262 } 263 264 /** 265 * Sets the previous port id. INVALID_PORT_ID invalidates it, hence no actions will be 266 * taken for <Inactive Source>. 267 */ 268 void setPrevPortId(int portId) { 269 synchronized (mLock) { 270 mPrevPortId = portId; 271 } 272 } 273 274 @ServiceThreadOnly 275 void updateActiveInput(int path, boolean notifyInputChange) { 276 assertRunOnServiceThread(); 277 // Seq #15 278 if (path == getActivePath()) { 279 return; 280 } 281 setPrevPortId(getActivePortId()); 282 setActivePath(path); 283 // TODO: Handle PAP/PIP case. 284 // Show OSD port change banner 285 if (notifyInputChange) { 286 ActiveSource activeSource = getActiveSource(); 287 HdmiDeviceInfo info = getCecDeviceInfo(activeSource.logicalAddress); 288 if (info == null) { 289 info = new HdmiDeviceInfo(Constants.ADDR_INVALID, path, getActivePortId(), 290 HdmiDeviceInfo.DEVICE_RESERVED, 0, null); 291 } 292 mService.invokeInputChangeListener(info); 293 } 294 } 295 296 @ServiceThreadOnly 297 void doManualPortSwitching(int portId, IHdmiControlCallback callback) { 298 assertRunOnServiceThread(); 299 // Seq #20 300 if (!mService.isValidPortId(portId)) { 301 invokeCallback(callback, HdmiControlManager.RESULT_INCORRECT_MODE); 302 return; 303 } 304 if (portId == getActivePortId()) { 305 invokeCallback(callback, HdmiControlManager.RESULT_SUCCESS); 306 return; 307 } 308 mActiveSource.invalidate(); 309 if (!mService.isControlEnabled()) { 310 setActivePortId(portId); 311 invokeCallback(callback, HdmiControlManager.RESULT_INCORRECT_MODE); 312 return; 313 } 314 int oldPath = getActivePortId() != Constants.INVALID_PORT_ID 315 ? mService.portIdToPath(getActivePortId()) : getDeviceInfo().getPhysicalAddress(); 316 setActivePath(oldPath); 317 if (mSkipRoutingControl) { 318 mSkipRoutingControl = false; 319 return; 320 } 321 int newPath = mService.portIdToPath(portId); 322 HdmiCecMessage routingChange = 323 HdmiCecMessageBuilder.buildRoutingChange(mAddress, oldPath, newPath); 324 mService.sendCecCommand(routingChange); 325 removeAction(RoutingControlAction.class); 326 addAndStartAction(new RoutingControlAction(this, newPath, true, callback)); 327 } 328 329 @ServiceThreadOnly 330 int getPowerStatus() { 331 assertRunOnServiceThread(); 332 return mService.getPowerStatus(); 333 } 334 335 /** 336 * Sends key to a target CEC device. 337 * 338 * @param keyCode key code to send. Defined in {@link android.view.KeyEvent}. 339 * @param isPressed true if this is key press event 340 */ 341 @Override 342 @ServiceThreadOnly 343 protected void sendKeyEvent(int keyCode, boolean isPressed) { 344 assertRunOnServiceThread(); 345 if (!HdmiCecKeycode.isSupportedKeycode(keyCode)) { 346 Slog.w(TAG, "Unsupported key: " + keyCode); 347 return; 348 } 349 List<SendKeyAction> action = getActions(SendKeyAction.class); 350 if (!action.isEmpty()) { 351 action.get(0).processKeyEvent(keyCode, isPressed); 352 } else { 353 if (isPressed && getActiveSource().isValid()) { 354 int logicalAddress = getActiveSource().logicalAddress; 355 addAndStartAction(new SendKeyAction(this, logicalAddress, keyCode)); 356 } else { 357 Slog.w(TAG, "Discard key event: " + keyCode + " pressed:" + isPressed); 358 } 359 } 360 } 361 362 private static void invokeCallback(IHdmiControlCallback callback, int result) { 363 if (callback == null) { 364 return; 365 } 366 try { 367 callback.onComplete(result); 368 } catch (RemoteException e) { 369 Slog.e(TAG, "Invoking callback failed:" + e); 370 } 371 } 372 373 @Override 374 @ServiceThreadOnly 375 protected boolean handleActiveSource(HdmiCecMessage message) { 376 assertRunOnServiceThread(); 377 int logicalAddress = message.getSource(); 378 int physicalAddress = HdmiUtils.twoBytesToInt(message.getParams()); 379 if (getCecDeviceInfo(logicalAddress) == null) { 380 handleNewDeviceAtTheTailOfActivePath(physicalAddress); 381 } else { 382 ActiveSource activeSource = ActiveSource.of(logicalAddress, physicalAddress); 383 ActiveSourceHandler.create(this, null).process(activeSource); 384 } 385 return true; 386 } 387 388 @Override 389 @ServiceThreadOnly 390 protected boolean handleInactiveSource(HdmiCecMessage message) { 391 assertRunOnServiceThread(); 392 // Seq #10 393 394 // Ignore <Inactive Source> from non-active source device. 395 if (getActiveSource().logicalAddress != message.getSource()) { 396 return true; 397 } 398 if (isProhibitMode()) { 399 return true; 400 } 401 int portId = getPrevPortId(); 402 if (portId != Constants.INVALID_PORT_ID) { 403 // TODO: Do this only if TV is not showing multiview like PIP/PAP. 404 405 HdmiDeviceInfo inactiveSource = getCecDeviceInfo(message.getSource()); 406 if (inactiveSource == null) { 407 return true; 408 } 409 if (mService.pathToPortId(inactiveSource.getPhysicalAddress()) == portId) { 410 return true; 411 } 412 // TODO: Switch the TV freeze mode off 413 414 doManualPortSwitching(portId, null); 415 setPrevPortId(Constants.INVALID_PORT_ID); 416 } 417 return true; 418 } 419 420 @Override 421 @ServiceThreadOnly 422 protected boolean handleRequestActiveSource(HdmiCecMessage message) { 423 assertRunOnServiceThread(); 424 // Seq #19 425 if (mAddress == getActiveSource().logicalAddress) { 426 mService.sendCecCommand( 427 HdmiCecMessageBuilder.buildActiveSource(mAddress, getActivePath())); 428 } 429 return true; 430 } 431 432 @Override 433 @ServiceThreadOnly 434 protected boolean handleGetMenuLanguage(HdmiCecMessage message) { 435 assertRunOnServiceThread(); 436 if (!broadcastMenuLanguage(mService.getLanguage())) { 437 Slog.w(TAG, "Failed to respond to <Get Menu Language>: " + message.toString()); 438 } 439 return true; 440 } 441 442 @ServiceThreadOnly 443 boolean broadcastMenuLanguage(String language) { 444 assertRunOnServiceThread(); 445 HdmiCecMessage command = HdmiCecMessageBuilder.buildSetMenuLanguageCommand( 446 mAddress, language); 447 if (command != null) { 448 mService.sendCecCommand(command); 449 return true; 450 } 451 return false; 452 } 453 454 @Override 455 @ServiceThreadOnly 456 protected boolean handleReportPhysicalAddress(HdmiCecMessage message) { 457 assertRunOnServiceThread(); 458 int path = HdmiUtils.twoBytesToInt(message.getParams()); 459 int address = message.getSource(); 460 int type = message.getParams()[2]; 461 462 if (updateCecSwitchInfo(address, type, path)) return true; 463 464 // Ignore if [Device Discovery Action] is going on. 465 if (hasAction(DeviceDiscoveryAction.class)) { 466 Slog.i(TAG, "Ignored while Device Discovery Action is in progress: " + message); 467 return true; 468 } 469 470 if (!isInDeviceList(address, path)) { 471 handleNewDeviceAtTheTailOfActivePath(path); 472 } 473 startNewDeviceAction(ActiveSource.of(address, path)); 474 return true; 475 } 476 477 @Override 478 protected boolean handleReportPowerStatus(HdmiCecMessage command) { 479 int newStatus = command.getParams()[0] & 0xFF; 480 updateDevicePowerStatus(command.getSource(), newStatus); 481 return true; 482 } 483 484 @Override 485 protected boolean handleTimerStatus(HdmiCecMessage message) { 486 // Do nothing. 487 return true; 488 } 489 490 @Override 491 protected boolean handleRecordStatus(HdmiCecMessage message) { 492 // Do nothing. 493 return true; 494 } 495 496 boolean updateCecSwitchInfo(int address, int type, int path) { 497 if (address == Constants.ADDR_UNREGISTERED 498 && type == HdmiDeviceInfo.DEVICE_PURE_CEC_SWITCH) { 499 mCecSwitches.add(path); 500 updateSafeDeviceInfoList(); 501 return true; // Pure switch does not need further processing. Return here. 502 } 503 if (type == HdmiDeviceInfo.DEVICE_AUDIO_SYSTEM) { 504 mCecSwitches.add(path); 505 } 506 return false; 507 } 508 509 void startNewDeviceAction(ActiveSource activeSource) { 510 for (NewDeviceAction action : getActions(NewDeviceAction.class)) { 511 // If there is new device action which has the same logical address and path 512 // ignore new request. 513 // NewDeviceAction is created whenever it receives <Report Physical Address>. 514 // And there is a chance starting NewDeviceAction for the same source. 515 // Usually, new device sends <Report Physical Address> when it's plugged 516 // in. However, TV can detect a new device from HotPlugDetectionAction, 517 // which sends <Give Physical Address> to the source for newly detected 518 // device. 519 if (action.isActionOf(activeSource)) { 520 return; 521 } 522 } 523 524 addAndStartAction(new NewDeviceAction(this, activeSource.logicalAddress, 525 activeSource.physicalAddress)); 526 } 527 528 private void handleNewDeviceAtTheTailOfActivePath(int path) { 529 // Seq #22 530 if (isTailOfActivePath(path, getActivePath())) { 531 removeAction(RoutingControlAction.class); 532 int newPath = mService.portIdToPath(getActivePortId()); 533 setActivePath(newPath); 534 mService.sendCecCommand(HdmiCecMessageBuilder.buildRoutingChange( 535 mAddress, getActivePath(), newPath)); 536 addAndStartAction(new RoutingControlAction(this, newPath, false, null)); 537 } 538 } 539 540 /** 541 * Whether the given path is located in the tail of current active path. 542 * 543 * @param path to be tested 544 * @param activePath current active path 545 * @return true if the given path is located in the tail of current active path; otherwise, 546 * false 547 */ 548 static boolean isTailOfActivePath(int path, int activePath) { 549 // If active routing path is internal source, return false. 550 if (activePath == 0) { 551 return false; 552 } 553 for (int i = 12; i >= 0; i -= 4) { 554 int curActivePath = (activePath >> i) & 0xF; 555 if (curActivePath == 0) { 556 return true; 557 } else { 558 int curPath = (path >> i) & 0xF; 559 if (curPath != curActivePath) { 560 return false; 561 } 562 } 563 } 564 return false; 565 } 566 567 @Override 568 @ServiceThreadOnly 569 protected boolean handleRoutingChange(HdmiCecMessage message) { 570 assertRunOnServiceThread(); 571 // Seq #21 572 byte[] params = message.getParams(); 573 int currentPath = HdmiUtils.twoBytesToInt(params); 574 if (HdmiUtils.isAffectingActiveRoutingPath(getActivePath(), currentPath)) { 575 mActiveSource.invalidate(); 576 removeAction(RoutingControlAction.class); 577 int newPath = HdmiUtils.twoBytesToInt(params, 2); 578 addAndStartAction(new RoutingControlAction(this, newPath, true, null)); 579 } 580 return true; 581 } 582 583 @Override 584 @ServiceThreadOnly 585 protected boolean handleReportAudioStatus(HdmiCecMessage message) { 586 assertRunOnServiceThread(); 587 588 byte params[] = message.getParams(); 589 int mute = params[0] & 0x80; 590 int volume = params[0] & 0x7F; 591 setAudioStatus(mute == 0x80, volume); 592 return true; 593 } 594 595 @Override 596 @ServiceThreadOnly 597 protected boolean handleTextViewOn(HdmiCecMessage message) { 598 assertRunOnServiceThread(); 599 if (mService.isPowerStandbyOrTransient() && mAutoWakeup) { 600 mService.wakeUp(); 601 } 602 return true; 603 } 604 605 @Override 606 @ServiceThreadOnly 607 protected boolean handleImageViewOn(HdmiCecMessage message) { 608 assertRunOnServiceThread(); 609 // Currently, it's the same as <Text View On>. 610 return handleTextViewOn(message); 611 } 612 613 @Override 614 @ServiceThreadOnly 615 protected boolean handleSetOsdName(HdmiCecMessage message) { 616 int source = message.getSource(); 617 HdmiDeviceInfo deviceInfo = getCecDeviceInfo(source); 618 // If the device is not in device list, ignore it. 619 if (deviceInfo == null) { 620 Slog.e(TAG, "No source device info for <Set Osd Name>." + message); 621 return true; 622 } 623 String osdName = null; 624 try { 625 osdName = new String(message.getParams(), "US-ASCII"); 626 } catch (UnsupportedEncodingException e) { 627 Slog.e(TAG, "Invalid <Set Osd Name> request:" + message, e); 628 return true; 629 } 630 631 if (deviceInfo.getDisplayName().equals(osdName)) { 632 Slog.i(TAG, "Ignore incoming <Set Osd Name> having same osd name:" + message); 633 return true; 634 } 635 636 addCecDevice(new HdmiDeviceInfo(deviceInfo.getLogicalAddress(), 637 deviceInfo.getPhysicalAddress(), deviceInfo.getPortId(), 638 deviceInfo.getDeviceType(), deviceInfo.getVendorId(), osdName)); 639 return true; 640 } 641 642 @ServiceThreadOnly 643 private void launchDeviceDiscovery() { 644 assertRunOnServiceThread(); 645 clearDeviceInfoList(); 646 DeviceDiscoveryAction action = new DeviceDiscoveryAction(this, 647 new DeviceDiscoveryCallback() { 648 @Override 649 public void onDeviceDiscoveryDone(List<HdmiDeviceInfo> deviceInfos) { 650 for (HdmiDeviceInfo info : deviceInfos) { 651 addCecDevice(info); 652 } 653 654 // Since we removed all devices when it's start and 655 // device discovery action does not poll local devices, 656 // we should put device info of local device manually here 657 for (HdmiCecLocalDevice device : mService.getAllLocalDevices()) { 658 addCecDevice(device.getDeviceInfo()); 659 } 660 661 addAndStartAction(new HotplugDetectionAction(HdmiCecLocalDeviceTv.this)); 662 addAndStartAction(new PowerStatusMonitorAction(HdmiCecLocalDeviceTv.this)); 663 664 // If there is AVR, initiate System Audio Auto initiation action, 665 // which turns on and off system audio according to last system 666 // audio setting. 667 HdmiDeviceInfo avr = getAvrDeviceInfo(); 668 if (avr != null) { 669 onNewAvrAdded(avr); 670 } 671 } 672 }); 673 addAndStartAction(action); 674 } 675 676 @ServiceThreadOnly 677 void onNewAvrAdded(HdmiDeviceInfo avr) { 678 assertRunOnServiceThread(); 679 if (getSystemAudioModeSetting()) { 680 addAndStartAction(new SystemAudioAutoInitiationAction(this, avr.getLogicalAddress())); 681 } 682 if (isArcFeatureEnabled()) { 683 startArcAction(true); 684 } 685 } 686 687 // Clear all device info. 688 @ServiceThreadOnly 689 private void clearDeviceInfoList() { 690 assertRunOnServiceThread(); 691 for (HdmiDeviceInfo info : mSafeExternalInputs) { 692 invokeDeviceEventListener(info, HdmiControlManager.DEVICE_EVENT_REMOVE_DEVICE); 693 } 694 mDeviceInfos.clear(); 695 updateSafeDeviceInfoList(); 696 } 697 698 @ServiceThreadOnly 699 // Seq #32 700 void changeSystemAudioMode(boolean enabled, IHdmiControlCallback callback) { 701 assertRunOnServiceThread(); 702 if (!mService.isControlEnabled() || hasAction(DeviceDiscoveryAction.class)) { 703 setSystemAudioMode(false, true); 704 invokeCallback(callback, HdmiControlManager.RESULT_INCORRECT_MODE); 705 return; 706 } 707 HdmiDeviceInfo avr = getAvrDeviceInfo(); 708 if (avr == null) { 709 setSystemAudioMode(false, true); 710 invokeCallback(callback, HdmiControlManager.RESULT_TARGET_NOT_AVAILABLE); 711 return; 712 } 713 714 addAndStartAction( 715 new SystemAudioActionFromTv(this, avr.getLogicalAddress(), enabled, callback)); 716 } 717 718 // # Seq 25 719 void setSystemAudioMode(boolean on, boolean updateSetting) { 720 HdmiLogger.debug("System Audio Mode change[old:%b new:%b]", mSystemAudioActivated, on); 721 722 if (updateSetting) { 723 mService.writeBooleanSetting(Global.HDMI_SYSTEM_AUDIO_ENABLED, on); 724 } 725 updateAudioManagerForSystemAudio(on); 726 synchronized (mLock) { 727 if (mSystemAudioActivated != on) { 728 mSystemAudioActivated = on; 729 mService.announceSystemAudioModeChange(on); 730 } 731 } 732 } 733 734 private void updateAudioManagerForSystemAudio(boolean on) { 735 mService.getAudioManager().setHdmiSystemAudioSupported(on); 736 } 737 738 boolean isSystemAudioActivated() { 739 if (getAvrDeviceInfo() == null) { 740 return false; 741 } 742 synchronized (mLock) { 743 return mSystemAudioActivated; 744 } 745 } 746 747 boolean getSystemAudioModeSetting() { 748 return mService.readBooleanSetting(Global.HDMI_SYSTEM_AUDIO_ENABLED, false); 749 } 750 751 /** 752 * Change ARC status into the given {@code enabled} status. 753 * 754 * @return {@code true} if ARC was in "Enabled" status 755 */ 756 @ServiceThreadOnly 757 boolean setArcStatus(boolean enabled) { 758 assertRunOnServiceThread(); 759 boolean oldStatus = mArcEstablished; 760 // 1. Enable/disable ARC circuit. 761 mService.setAudioReturnChannel(enabled); 762 // 2. Notify arc status to audio service. 763 notifyArcStatusToAudioService(enabled); 764 // 3. Update arc status; 765 mArcEstablished = enabled; 766 return oldStatus; 767 } 768 769 private void notifyArcStatusToAudioService(boolean enabled) { 770 // Note that we don't set any name to ARC. 771 mService.getAudioManager().setWiredDeviceConnectionState( 772 AudioSystem.DEVICE_OUT_HDMI_ARC, 773 enabled ? 1 : 0, ""); 774 } 775 776 /** 777 * Returns whether ARC is enabled or not. 778 */ 779 @ServiceThreadOnly 780 boolean isArcEstabilished() { 781 assertRunOnServiceThread(); 782 return mArcFeatureEnabled && mArcEstablished; 783 } 784 785 @ServiceThreadOnly 786 void changeArcFeatureEnabled(boolean enabled) { 787 assertRunOnServiceThread(); 788 789 if (mArcFeatureEnabled != enabled) { 790 mArcFeatureEnabled = enabled; 791 if (enabled) { 792 if (!mArcEstablished) { 793 startArcAction(true); 794 } 795 } else { 796 if (mArcEstablished) { 797 startArcAction(false); 798 } 799 } 800 } 801 } 802 803 @ServiceThreadOnly 804 boolean isArcFeatureEnabled() { 805 assertRunOnServiceThread(); 806 return mArcFeatureEnabled; 807 } 808 809 @ServiceThreadOnly 810 void startArcAction(boolean enabled) { 811 assertRunOnServiceThread(); 812 HdmiDeviceInfo info = getAvrDeviceInfo(); 813 if (info == null) { 814 Slog.w(TAG, "Failed to start arc action; No AVR device."); 815 return; 816 } 817 if (!canStartArcUpdateAction(info.getLogicalAddress(), enabled)) { 818 Slog.w(TAG, "Failed to start arc action; ARC configuration check failed."); 819 if (enabled && !isConnectedToArcPort(info.getPhysicalAddress())) { 820 displayOsd(OSD_MESSAGE_ARC_CONNECTED_INVALID_PORT); 821 } 822 return; 823 } 824 825 // Terminate opposite action and start action if not exist. 826 if (enabled) { 827 removeAction(RequestArcTerminationAction.class); 828 if (!hasAction(RequestArcInitiationAction.class)) { 829 addAndStartAction(new RequestArcInitiationAction(this, info.getLogicalAddress())); 830 } 831 } else { 832 removeAction(RequestArcInitiationAction.class); 833 if (!hasAction(RequestArcTerminationAction.class)) { 834 addAndStartAction(new RequestArcTerminationAction(this, info.getLogicalAddress())); 835 } 836 } 837 } 838 839 private boolean isDirectConnectAddress(int physicalAddress) { 840 return (physicalAddress & Constants.ROUTING_PATH_TOP_MASK) == physicalAddress; 841 } 842 843 void setAudioStatus(boolean mute, int volume) { 844 synchronized (mLock) { 845 mSystemAudioMute = mute; 846 mSystemAudioVolume = volume; 847 int maxVolume = mService.getAudioManager().getStreamMaxVolume( 848 AudioManager.STREAM_MUSIC); 849 mService.setAudioStatus(mute, 850 VolumeControlAction.scaleToCustomVolume(volume, maxVolume)); 851 displayOsd(HdmiControlManager.OSD_MESSAGE_AVR_VOLUME_CHANGED, 852 mute ? HdmiControlManager.AVR_VOLUME_MUTED : volume); 853 } 854 } 855 856 @ServiceThreadOnly 857 void changeVolume(int curVolume, int delta, int maxVolume) { 858 assertRunOnServiceThread(); 859 if (delta == 0 || !isSystemAudioActivated()) { 860 return; 861 } 862 863 int targetVolume = curVolume + delta; 864 int cecVolume = VolumeControlAction.scaleToCecVolume(targetVolume, maxVolume); 865 synchronized (mLock) { 866 // If new volume is the same as current system audio volume, just ignore it. 867 // Note that UNKNOWN_VOLUME is not in range of cec volume scale. 868 if (cecVolume == mSystemAudioVolume) { 869 // Update tv volume with system volume value. 870 mService.setAudioStatus(false, 871 VolumeControlAction.scaleToCustomVolume(mSystemAudioVolume, maxVolume)); 872 return; 873 } 874 } 875 876 List<VolumeControlAction> actions = getActions(VolumeControlAction.class); 877 if (actions.isEmpty()) { 878 addAndStartAction(new VolumeControlAction(this, 879 getAvrDeviceInfo().getLogicalAddress(), delta > 0)); 880 } else { 881 actions.get(0).handleVolumeChange(delta > 0); 882 } 883 } 884 885 @ServiceThreadOnly 886 void changeMute(boolean mute) { 887 assertRunOnServiceThread(); 888 if (!isSystemAudioActivated()) { 889 return; 890 } 891 892 // Remove existing volume action. 893 removeAction(VolumeControlAction.class); 894 sendUserControlPressedAndReleased(getAvrDeviceInfo().getLogicalAddress(), 895 mute ? HdmiCecKeycode.CEC_KEYCODE_MUTE_FUNCTION : 896 HdmiCecKeycode.CEC_KEYCODE_RESTORE_VOLUME_FUNCTION); 897 } 898 899 @Override 900 @ServiceThreadOnly 901 protected boolean handleInitiateArc(HdmiCecMessage message) { 902 assertRunOnServiceThread(); 903 904 if (!canStartArcUpdateAction(message.getSource(), true)) { 905 mService.maySendFeatureAbortCommand(message, Constants.ABORT_REFUSED); 906 if (!isConnectedToArcPort(message.getSource())) { 907 displayOsd(OSD_MESSAGE_ARC_CONNECTED_INVALID_PORT); 908 } 909 return true; 910 } 911 912 // In case where <Initiate Arc> is started by <Request ARC Initiation> 913 // need to clean up RequestArcInitiationAction. 914 removeAction(RequestArcInitiationAction.class); 915 SetArcTransmissionStateAction action = new SetArcTransmissionStateAction(this, 916 message.getSource(), true); 917 addAndStartAction(action); 918 return true; 919 } 920 921 private boolean canStartArcUpdateAction(int avrAddress, boolean shouldCheckArcFeatureEnabled) { 922 HdmiDeviceInfo avr = getAvrDeviceInfo(); 923 if (avr != null 924 && (avrAddress == avr.getLogicalAddress()) 925 && isConnectedToArcPort(avr.getPhysicalAddress()) 926 && isDirectConnectAddress(avr.getPhysicalAddress())) { 927 if (shouldCheckArcFeatureEnabled) { 928 return isArcFeatureEnabled(); 929 } else { 930 return true; 931 } 932 } else { 933 return false; 934 } 935 } 936 937 @Override 938 @ServiceThreadOnly 939 protected boolean handleTerminateArc(HdmiCecMessage message) { 940 assertRunOnServiceThread(); 941 // In cast of termination, do not check ARC configuration in that AVR device 942 // might be removed already. 943 944 // In case where <Terminate Arc> is started by <Request ARC Termination> 945 // need to clean up RequestArcInitiationAction. 946 removeAction(RequestArcTerminationAction.class); 947 SetArcTransmissionStateAction action = new SetArcTransmissionStateAction(this, 948 message.getSource(), false); 949 addAndStartAction(action); 950 return true; 951 } 952 953 @Override 954 @ServiceThreadOnly 955 protected boolean handleSetSystemAudioMode(HdmiCecMessage message) { 956 assertRunOnServiceThread(); 957 if (!isMessageForSystemAudio(message)) { 958 HdmiLogger.warning("Invalid <Set System Audio Mode> message:" + message); 959 mService.maySendFeatureAbortCommand(message, Constants.ABORT_REFUSED); 960 return true; 961 } 962 SystemAudioActionFromAvr action = new SystemAudioActionFromAvr(this, 963 message.getSource(), HdmiUtils.parseCommandParamSystemAudioStatus(message), null); 964 addAndStartAction(action); 965 return true; 966 } 967 968 @Override 969 @ServiceThreadOnly 970 protected boolean handleSystemAudioModeStatus(HdmiCecMessage message) { 971 assertRunOnServiceThread(); 972 if (!isMessageForSystemAudio(message)) { 973 HdmiLogger.warning("Invalid <System Audio Mode Status> message:" + message); 974 // Ignore this message. 975 return true; 976 } 977 setSystemAudioMode(HdmiUtils.parseCommandParamSystemAudioStatus(message), true); 978 return true; 979 } 980 981 // Seq #53 982 @Override 983 @ServiceThreadOnly 984 protected boolean handleRecordTvScreen(HdmiCecMessage message) { 985 List<OneTouchRecordAction> actions = getActions(OneTouchRecordAction.class); 986 if (!actions.isEmpty()) { 987 // Assumes only one OneTouchRecordAction. 988 OneTouchRecordAction action = actions.get(0); 989 if (action.getRecorderAddress() != message.getSource()) { 990 announceOneTouchRecordResult( 991 HdmiControlManager.ONE_TOUCH_RECORD_PREVIOUS_RECORDING_IN_PROGRESS); 992 } 993 return super.handleRecordTvScreen(message); 994 } 995 996 int recorderAddress = message.getSource(); 997 byte[] recordSource = mService.invokeRecordRequestListener(recorderAddress); 998 int reason = startOneTouchRecord(recorderAddress, recordSource); 999 if (reason != Constants.ABORT_NO_ERROR) { 1000 mService.maySendFeatureAbortCommand(message, reason); 1001 } 1002 return true; 1003 } 1004 1005 @Override 1006 protected boolean handleTimerClearedStatus(HdmiCecMessage message) { 1007 byte[] params = message.getParams(); 1008 int timerClearedStatusData = params[0] & 0xFF; 1009 announceTimerRecordingResult(timerClearedStatusData); 1010 return true; 1011 } 1012 1013 void announceOneTouchRecordResult(int result) { 1014 mService.invokeOneTouchRecordResult(result); 1015 } 1016 1017 void announceTimerRecordingResult(int result) { 1018 mService.invokeTimerRecordingResult(result); 1019 } 1020 1021 void announceClearTimerRecordingResult(int result) { 1022 mService.invokeClearTimerRecordingResult(result); 1023 } 1024 1025 private boolean isMessageForSystemAudio(HdmiCecMessage message) { 1026 return mService.isControlEnabled() 1027 && message.getSource() == Constants.ADDR_AUDIO_SYSTEM 1028 && (message.getDestination() == Constants.ADDR_TV 1029 || message.getDestination() == Constants.ADDR_BROADCAST) 1030 && getAvrDeviceInfo() != null; 1031 } 1032 1033 /** 1034 * Add a new {@link HdmiDeviceInfo}. It returns old device info which has the same 1035 * logical address as new device info's. 1036 * 1037 * <p>Declared as package-private. accessed by {@link HdmiControlService} only. 1038 * 1039 * @param deviceInfo a new {@link HdmiDeviceInfo} to be added. 1040 * @return {@code null} if it is new device. Otherwise, returns old {@HdmiDeviceInfo} 1041 * that has the same logical address as new one has. 1042 */ 1043 @ServiceThreadOnly 1044 private HdmiDeviceInfo addDeviceInfo(HdmiDeviceInfo deviceInfo) { 1045 assertRunOnServiceThread(); 1046 HdmiDeviceInfo oldDeviceInfo = getCecDeviceInfo(deviceInfo.getLogicalAddress()); 1047 if (oldDeviceInfo != null) { 1048 removeDeviceInfo(deviceInfo.getId()); 1049 } 1050 mDeviceInfos.append(deviceInfo.getId(), deviceInfo); 1051 updateSafeDeviceInfoList(); 1052 return oldDeviceInfo; 1053 } 1054 1055 /** 1056 * Remove a device info corresponding to the given {@code logicalAddress}. 1057 * It returns removed {@link HdmiDeviceInfo} if exists. 1058 * 1059 * <p>Declared as package-private. accessed by {@link HdmiControlService} only. 1060 * 1061 * @param id id of device to be removed 1062 * @return removed {@link HdmiDeviceInfo} it exists. Otherwise, returns {@code null} 1063 */ 1064 @ServiceThreadOnly 1065 private HdmiDeviceInfo removeDeviceInfo(int id) { 1066 assertRunOnServiceThread(); 1067 HdmiDeviceInfo deviceInfo = mDeviceInfos.get(id); 1068 if (deviceInfo != null) { 1069 mDeviceInfos.remove(id); 1070 } 1071 updateSafeDeviceInfoList(); 1072 return deviceInfo; 1073 } 1074 1075 /** 1076 * Return a list of all {@link HdmiDeviceInfo}. 1077 * 1078 * <p>Declared as package-private. accessed by {@link HdmiControlService} only. 1079 * This is not thread-safe. For thread safety, call {@link #getSafeExternalInputsLocked} which 1080 * does not include local device. 1081 */ 1082 @ServiceThreadOnly 1083 List<HdmiDeviceInfo> getDeviceInfoList(boolean includeLocalDevice) { 1084 assertRunOnServiceThread(); 1085 if (includeLocalDevice) { 1086 return HdmiUtils.sparseArrayToList(mDeviceInfos); 1087 } else { 1088 ArrayList<HdmiDeviceInfo> infoList = new ArrayList<>(); 1089 for (int i = 0; i < mDeviceInfos.size(); ++i) { 1090 HdmiDeviceInfo info = mDeviceInfos.valueAt(i); 1091 if (!isLocalDeviceAddress(info.getLogicalAddress())) { 1092 infoList.add(info); 1093 } 1094 } 1095 return infoList; 1096 } 1097 } 1098 1099 /** 1100 * Return external input devices. 1101 */ 1102 List<HdmiDeviceInfo> getSafeExternalInputsLocked() { 1103 return mSafeExternalInputs; 1104 } 1105 1106 @ServiceThreadOnly 1107 private void updateSafeDeviceInfoList() { 1108 assertRunOnServiceThread(); 1109 List<HdmiDeviceInfo> copiedDevices = HdmiUtils.sparseArrayToList(mDeviceInfos); 1110 List<HdmiDeviceInfo> externalInputs = getInputDevices(); 1111 synchronized (mLock) { 1112 mSafeAllDeviceInfos = copiedDevices; 1113 mSafeExternalInputs = externalInputs; 1114 } 1115 } 1116 1117 /** 1118 * Return a list of external cec input (source) devices. 1119 * 1120 * <p>Note that this effectively excludes non-source devices like system audio, 1121 * secondary TV. 1122 */ 1123 private List<HdmiDeviceInfo> getInputDevices() { 1124 ArrayList<HdmiDeviceInfo> infoList = new ArrayList<>(); 1125 for (int i = 0; i < mDeviceInfos.size(); ++i) { 1126 HdmiDeviceInfo info = mDeviceInfos.valueAt(i); 1127 if (isLocalDeviceAddress(info.getLogicalAddress())) { 1128 continue; 1129 } 1130 if (info.isSourceType() && !hideDevicesBehindLegacySwitch(info)) { 1131 infoList.add(info); 1132 } 1133 } 1134 return infoList; 1135 } 1136 1137 // Check if we are hiding CEC devices connected to a legacy (non-CEC) switch. 1138 // Returns true if the policy is set to true, and the device to check does not have 1139 // a parent CEC device (which should be the CEC-enabled switch) in the list. 1140 private boolean hideDevicesBehindLegacySwitch(HdmiDeviceInfo info) { 1141 return HdmiConfig.HIDE_DEVICES_BEHIND_LEGACY_SWITCH 1142 && !isConnectedToCecSwitch(info.getPhysicalAddress(), mCecSwitches); 1143 } 1144 1145 private static boolean isConnectedToCecSwitch(int path, Collection<Integer> switches) { 1146 for (int switchPath : switches) { 1147 if (isParentPath(switchPath, path)) { 1148 return true; 1149 } 1150 } 1151 return false; 1152 } 1153 1154 private static boolean isParentPath(int parentPath, int childPath) { 1155 // (A000, AB00) (AB00, ABC0), (ABC0, ABCD) 1156 // If child's last non-zero nibble is removed, the result equals to the parent. 1157 for (int i = 0; i <= 12; i += 4) { 1158 int nibble = (childPath >> i) & 0xF; 1159 if (nibble != 0) { 1160 int parentNibble = (parentPath >> i) & 0xF; 1161 return parentNibble == 0 && (childPath >> i+4) == (parentPath >> i+4); 1162 } 1163 } 1164 return false; 1165 } 1166 1167 private void invokeDeviceEventListener(HdmiDeviceInfo info, int status) { 1168 if (info.isSourceType() && !hideDevicesBehindLegacySwitch(info)) { 1169 mService.invokeDeviceEventListeners(info, status); 1170 } 1171 } 1172 1173 @ServiceThreadOnly 1174 private boolean isLocalDeviceAddress(int address) { 1175 assertRunOnServiceThread(); 1176 for (HdmiCecLocalDevice device : mService.getAllLocalDevices()) { 1177 if (device.isAddressOf(address)) { 1178 return true; 1179 } 1180 } 1181 return false; 1182 } 1183 1184 @ServiceThreadOnly 1185 HdmiDeviceInfo getAvrDeviceInfo() { 1186 assertRunOnServiceThread(); 1187 return getCecDeviceInfo(Constants.ADDR_AUDIO_SYSTEM); 1188 } 1189 1190 /** 1191 * Return a {@link HdmiDeviceInfo} corresponding to the given {@code logicalAddress}. 1192 * 1193 * This is not thread-safe. For thread safety, call {@link #getSafeCecDeviceInfo(int)}. 1194 * 1195 * @param logicalAddress logical address of the device to be retrieved 1196 * @return {@link HdmiDeviceInfo} matched with the given {@code logicalAddress}. 1197 * Returns null if no logical address matched 1198 */ 1199 @ServiceThreadOnly 1200 HdmiDeviceInfo getCecDeviceInfo(int logicalAddress) { 1201 assertRunOnServiceThread(); 1202 return mDeviceInfos.get(HdmiDeviceInfo.idForCecDevice(logicalAddress)); 1203 } 1204 1205 boolean hasSystemAudioDevice() { 1206 return getSafeAvrDeviceInfo() != null; 1207 } 1208 1209 HdmiDeviceInfo getSafeAvrDeviceInfo() { 1210 return getSafeCecDeviceInfo(Constants.ADDR_AUDIO_SYSTEM); 1211 } 1212 1213 /** 1214 * Thread safe version of {@link #getCecDeviceInfo(int)}. 1215 * 1216 * @param logicalAddress logical address to be retrieved 1217 * @return {@link HdmiDeviceInfo} matched with the given {@code logicalAddress}. 1218 * Returns null if no logical address matched 1219 */ 1220 HdmiDeviceInfo getSafeCecDeviceInfo(int logicalAddress) { 1221 synchronized (mLock) { 1222 for (HdmiDeviceInfo info : mSafeAllDeviceInfos) { 1223 if (info.isCecDevice() && info.getLogicalAddress() == logicalAddress) { 1224 return info; 1225 } 1226 } 1227 return null; 1228 } 1229 } 1230 1231 /** 1232 * Called when a device is newly added or a new device is detected or 1233 * existing device is updated. 1234 * 1235 * @param info device info of a new device. 1236 */ 1237 @ServiceThreadOnly 1238 final void addCecDevice(HdmiDeviceInfo info) { 1239 assertRunOnServiceThread(); 1240 addDeviceInfo(info); 1241 if (info.getLogicalAddress() == mAddress) { 1242 // The addition of TV device itself should not be notified. 1243 return; 1244 } 1245 invokeDeviceEventListener(info, HdmiControlManager.DEVICE_EVENT_ADD_DEVICE); 1246 } 1247 1248 /** 1249 * Called when a device is removed or removal of device is detected. 1250 * 1251 * @param address a logical address of a device to be removed 1252 */ 1253 @ServiceThreadOnly 1254 final void removeCecDevice(int address) { 1255 assertRunOnServiceThread(); 1256 HdmiDeviceInfo info = removeDeviceInfo(HdmiDeviceInfo.idForCecDevice(address)); 1257 1258 mCecMessageCache.flushMessagesFrom(address); 1259 invokeDeviceEventListener(info, HdmiControlManager.DEVICE_EVENT_REMOVE_DEVICE); 1260 } 1261 1262 @ServiceThreadOnly 1263 void handleRemoveActiveRoutingPath(int path) { 1264 assertRunOnServiceThread(); 1265 // Seq #23 1266 if (isTailOfActivePath(path, getActivePath())) { 1267 removeAction(RoutingControlAction.class); 1268 int newPath = mService.portIdToPath(getActivePortId()); 1269 mService.sendCecCommand(HdmiCecMessageBuilder.buildRoutingChange( 1270 mAddress, getActivePath(), newPath)); 1271 mActiveSource.invalidate(); 1272 addAndStartAction(new RoutingControlAction(this, getActivePath(), true, null)); 1273 } 1274 } 1275 1276 /** 1277 * Launch routing control process. 1278 * 1279 * @param routingForBootup true if routing control is initiated due to One Touch Play 1280 * or TV power on 1281 */ 1282 @ServiceThreadOnly 1283 void launchRoutingControl(boolean routingForBootup) { 1284 assertRunOnServiceThread(); 1285 // Seq #24 1286 if (getActivePortId() != Constants.INVALID_PORT_ID) { 1287 if (!routingForBootup && !isProhibitMode()) { 1288 removeAction(RoutingControlAction.class); 1289 int newPath = mService.portIdToPath(getActivePortId()); 1290 setActivePath(newPath); 1291 mService.sendCecCommand(HdmiCecMessageBuilder.buildRoutingChange(mAddress, 1292 getActivePath(), newPath)); 1293 addAndStartAction(new RoutingControlAction(this, getActivePortId(), 1294 routingForBootup, null)); 1295 } 1296 } else { 1297 int activePath = mService.getPhysicalAddress(); 1298 setActivePath(activePath); 1299 if (!routingForBootup) { 1300 mService.sendCecCommand(HdmiCecMessageBuilder.buildActiveSource(mAddress, 1301 activePath)); 1302 } 1303 } 1304 } 1305 1306 /** 1307 * Returns the {@link HdmiDeviceInfo} instance whose physical address matches 1308 * the given routing path. CEC devices use routing path for its physical address to 1309 * describe the hierarchy of the devices in the network. 1310 * 1311 * @param path routing path or physical address 1312 * @return {@link HdmiDeviceInfo} if the matched info is found; otherwise null 1313 */ 1314 @ServiceThreadOnly 1315 final HdmiDeviceInfo getDeviceInfoByPath(int path) { 1316 assertRunOnServiceThread(); 1317 for (HdmiDeviceInfo info : getDeviceInfoList(false)) { 1318 if (info.getPhysicalAddress() == path) { 1319 return info; 1320 } 1321 } 1322 return null; 1323 } 1324 1325 /** 1326 * Whether a device of the specified physical address and logical address exists 1327 * in a device info list. However, both are minimal condition and it could 1328 * be different device from the original one. 1329 * 1330 * @param logicalAddress logical address of a device to be searched 1331 * @param physicalAddress physical address of a device to be searched 1332 * @return true if exist; otherwise false 1333 */ 1334 @ServiceThreadOnly 1335 private boolean isInDeviceList(int logicalAddress, int physicalAddress) { 1336 assertRunOnServiceThread(); 1337 HdmiDeviceInfo device = getCecDeviceInfo(logicalAddress); 1338 if (device == null) { 1339 return false; 1340 } 1341 return device.getPhysicalAddress() == physicalAddress; 1342 } 1343 1344 @Override 1345 @ServiceThreadOnly 1346 void onHotplug(int portId, boolean connected) { 1347 assertRunOnServiceThread(); 1348 1349 if (!connected) { 1350 removeCecSwitches(portId); 1351 } 1352 // Tv device will have permanent HotplugDetectionAction. 1353 List<HotplugDetectionAction> hotplugActions = getActions(HotplugDetectionAction.class); 1354 if (!hotplugActions.isEmpty()) { 1355 // Note that hotplug action is single action running on a machine. 1356 // "pollAllDevicesNow" cleans up timer and start poll action immediately. 1357 // It covers seq #40, #43. 1358 hotplugActions.get(0).pollAllDevicesNow(); 1359 } 1360 } 1361 1362 private void removeCecSwitches(int portId) { 1363 Iterator<Integer> it = mCecSwitches.iterator(); 1364 while (!it.hasNext()) { 1365 int path = it.next(); 1366 if (pathToPortId(path) == portId) { 1367 it.remove(); 1368 } 1369 } 1370 } 1371 1372 @ServiceThreadOnly 1373 void setAutoDeviceOff(boolean enabled) { 1374 assertRunOnServiceThread(); 1375 mAutoDeviceOff = enabled; 1376 } 1377 1378 @ServiceThreadOnly 1379 void setAutoWakeup(boolean enabled) { 1380 assertRunOnServiceThread(); 1381 mAutoWakeup = enabled; 1382 } 1383 1384 @ServiceThreadOnly 1385 boolean getAutoWakeup() { 1386 assertRunOnServiceThread(); 1387 return mAutoWakeup; 1388 } 1389 1390 @Override 1391 @ServiceThreadOnly 1392 protected void disableDevice(boolean initiatedByCec, PendingActionClearedCallback callback) { 1393 super.disableDevice(initiatedByCec, callback); 1394 assertRunOnServiceThread(); 1395 // Remove any repeated working actions. 1396 // HotplugDetectionAction will be reinstated during the wake up process. 1397 // HdmiControlService.onWakeUp() -> initializeLocalDevices() -> 1398 // LocalDeviceTv.onAddressAllocated() -> launchDeviceDiscovery(). 1399 removeAction(DeviceDiscoveryAction.class); 1400 removeAction(HotplugDetectionAction.class); 1401 removeAction(PowerStatusMonitorAction.class); 1402 // Remove recording actions. 1403 removeAction(OneTouchRecordAction.class); 1404 removeAction(TimerRecordingAction.class); 1405 1406 disableSystemAudioIfExist(); 1407 disableArcIfExist(); 1408 clearDeviceInfoList(); 1409 checkIfPendingActionsCleared(); 1410 } 1411 1412 @ServiceThreadOnly 1413 private void disableSystemAudioIfExist() { 1414 assertRunOnServiceThread(); 1415 if (getAvrDeviceInfo() == null) { 1416 return; 1417 } 1418 1419 // Seq #31. 1420 removeAction(SystemAudioActionFromAvr.class); 1421 removeAction(SystemAudioActionFromTv.class); 1422 removeAction(SystemAudioAutoInitiationAction.class); 1423 removeAction(SystemAudioStatusAction.class); 1424 removeAction(VolumeControlAction.class); 1425 1426 // Turn off the mode but do not write it the settings, so that the next time TV powers on 1427 // the system audio mode setting can be restored automatically. 1428 setSystemAudioMode(false, false); 1429 } 1430 1431 @ServiceThreadOnly 1432 private void disableArcIfExist() { 1433 assertRunOnServiceThread(); 1434 HdmiDeviceInfo avr = getAvrDeviceInfo(); 1435 if (avr == null) { 1436 return; 1437 } 1438 1439 // Seq #44. 1440 removeAction(RequestArcInitiationAction.class); 1441 if (!hasAction(RequestArcTerminationAction.class) && isArcEstabilished()) { 1442 addAndStartAction(new RequestArcTerminationAction(this, avr.getLogicalAddress())); 1443 } 1444 } 1445 1446 @Override 1447 @ServiceThreadOnly 1448 protected void onStandby(boolean initiatedByCec) { 1449 assertRunOnServiceThread(); 1450 // Seq #11 1451 if (!mService.isControlEnabled()) { 1452 return; 1453 } 1454 if (!initiatedByCec && mAutoDeviceOff) { 1455 mService.sendCecCommand(HdmiCecMessageBuilder.buildStandby( 1456 mAddress, Constants.ADDR_BROADCAST)); 1457 } 1458 } 1459 1460 boolean isProhibitMode() { 1461 return mService.isProhibitMode(); 1462 } 1463 1464 boolean isPowerStandbyOrTransient() { 1465 return mService.isPowerStandbyOrTransient(); 1466 } 1467 1468 @ServiceThreadOnly 1469 void displayOsd(int messageId) { 1470 assertRunOnServiceThread(); 1471 mService.displayOsd(messageId); 1472 } 1473 1474 @ServiceThreadOnly 1475 void displayOsd(int messageId, int extra) { 1476 assertRunOnServiceThread(); 1477 mService.displayOsd(messageId, extra); 1478 } 1479 1480 // Seq #54 and #55 1481 @ServiceThreadOnly 1482 int startOneTouchRecord(int recorderAddress, byte[] recordSource) { 1483 assertRunOnServiceThread(); 1484 if (!mService.isControlEnabled()) { 1485 Slog.w(TAG, "Can not start one touch record. CEC control is disabled."); 1486 announceOneTouchRecordResult(ONE_TOUCH_RECORD_CEC_DISABLED); 1487 return Constants.ABORT_NOT_IN_CORRECT_MODE; 1488 } 1489 1490 if (!checkRecorder(recorderAddress)) { 1491 Slog.w(TAG, "Invalid recorder address:" + recorderAddress); 1492 announceOneTouchRecordResult(ONE_TOUCH_RECORD_CHECK_RECORDER_CONNECTION); 1493 return Constants.ABORT_NOT_IN_CORRECT_MODE; 1494 } 1495 1496 if (!checkRecordSource(recordSource)) { 1497 Slog.w(TAG, "Invalid record source." + Arrays.toString(recordSource)); 1498 announceOneTouchRecordResult(ONE_TOUCH_RECORD_FAIL_TO_RECORD_DISPLAYED_SCREEN); 1499 return Constants.ABORT_UNABLE_TO_DETERMINE; 1500 } 1501 1502 addAndStartAction(new OneTouchRecordAction(this, recorderAddress, recordSource)); 1503 Slog.i(TAG, "Start new [One Touch Record]-Target:" + recorderAddress + ", recordSource:" 1504 + Arrays.toString(recordSource)); 1505 return Constants.ABORT_NO_ERROR; 1506 } 1507 1508 @ServiceThreadOnly 1509 void stopOneTouchRecord(int recorderAddress) { 1510 assertRunOnServiceThread(); 1511 if (!mService.isControlEnabled()) { 1512 Slog.w(TAG, "Can not stop one touch record. CEC control is disabled."); 1513 announceOneTouchRecordResult(ONE_TOUCH_RECORD_CEC_DISABLED); 1514 return; 1515 } 1516 1517 if (!checkRecorder(recorderAddress)) { 1518 Slog.w(TAG, "Invalid recorder address:" + recorderAddress); 1519 announceOneTouchRecordResult(ONE_TOUCH_RECORD_CHECK_RECORDER_CONNECTION); 1520 return; 1521 } 1522 1523 // Remove one touch record action so that other one touch record can be started. 1524 removeAction(OneTouchRecordAction.class); 1525 mService.sendCecCommand(HdmiCecMessageBuilder.buildRecordOff(mAddress, recorderAddress)); 1526 Slog.i(TAG, "Stop [One Touch Record]-Target:" + recorderAddress); 1527 } 1528 1529 private boolean checkRecorder(int recorderAddress) { 1530 HdmiDeviceInfo device = getCecDeviceInfo(recorderAddress); 1531 return (device != null) 1532 && (HdmiUtils.getTypeFromAddress(recorderAddress) 1533 == HdmiDeviceInfo.DEVICE_RECORDER); 1534 } 1535 1536 private boolean checkRecordSource(byte[] recordSource) { 1537 return (recordSource != null) && HdmiRecordSources.checkRecordSource(recordSource); 1538 } 1539 1540 @ServiceThreadOnly 1541 void startTimerRecording(int recorderAddress, int sourceType, byte[] recordSource) { 1542 assertRunOnServiceThread(); 1543 if (!mService.isControlEnabled()) { 1544 Slog.w(TAG, "Can not start one touch record. CEC control is disabled."); 1545 announceTimerRecordingResult(TIMER_RECORDING_RESULT_EXTRA_CEC_DISABLED); 1546 return; 1547 } 1548 1549 if (!checkRecorder(recorderAddress)) { 1550 Slog.w(TAG, "Invalid recorder address:" + recorderAddress); 1551 announceTimerRecordingResult( 1552 TIMER_RECORDING_RESULT_EXTRA_CHECK_RECORDER_CONNECTION); 1553 return; 1554 } 1555 1556 if (!checkTimerRecordingSource(sourceType, recordSource)) { 1557 Slog.w(TAG, "Invalid record source." + Arrays.toString(recordSource)); 1558 announceTimerRecordingResult( 1559 TIMER_RECORDING_RESULT_EXTRA_FAIL_TO_RECORD_SELECTED_SOURCE); 1560 return; 1561 } 1562 1563 addAndStartAction( 1564 new TimerRecordingAction(this, recorderAddress, sourceType, recordSource)); 1565 Slog.i(TAG, "Start [Timer Recording]-Target:" + recorderAddress + ", SourceType:" 1566 + sourceType + ", RecordSource:" + Arrays.toString(recordSource)); 1567 } 1568 1569 private boolean checkTimerRecordingSource(int sourceType, byte[] recordSource) { 1570 return (recordSource != null) 1571 && HdmiTimerRecordSources.checkTimerRecordSource(sourceType, recordSource); 1572 } 1573 1574 @ServiceThreadOnly 1575 void clearTimerRecording(int recorderAddress, int sourceType, byte[] recordSource) { 1576 assertRunOnServiceThread(); 1577 if (!mService.isControlEnabled()) { 1578 Slog.w(TAG, "Can not start one touch record. CEC control is disabled."); 1579 announceClearTimerRecordingResult(CLEAR_TIMER_STATUS_CEC_DISABLE); 1580 return; 1581 } 1582 1583 if (!checkRecorder(recorderAddress)) { 1584 Slog.w(TAG, "Invalid recorder address:" + recorderAddress); 1585 announceClearTimerRecordingResult(CLEAR_TIMER_STATUS_CHECK_RECORDER_CONNECTION); 1586 return; 1587 } 1588 1589 if (!checkTimerRecordingSource(sourceType, recordSource)) { 1590 Slog.w(TAG, "Invalid record source." + Arrays.toString(recordSource)); 1591 announceClearTimerRecordingResult(CLEAR_TIMER_STATUS_FAIL_TO_CLEAR_SELECTED_SOURCE); 1592 return; 1593 } 1594 1595 sendClearTimerMessage(recorderAddress, sourceType, recordSource); 1596 } 1597 1598 private void sendClearTimerMessage(int recorderAddress, int sourceType, byte[] recordSource) { 1599 HdmiCecMessage message = null; 1600 switch (sourceType) { 1601 case TIMER_RECORDING_TYPE_DIGITAL: 1602 message = HdmiCecMessageBuilder.buildClearDigitalTimer(mAddress, recorderAddress, 1603 recordSource); 1604 break; 1605 case TIMER_RECORDING_TYPE_ANALOGUE: 1606 message = HdmiCecMessageBuilder.buildClearAnalogueTimer(mAddress, recorderAddress, 1607 recordSource); 1608 break; 1609 case TIMER_RECORDING_TYPE_EXTERNAL: 1610 message = HdmiCecMessageBuilder.buildClearExternalTimer(mAddress, recorderAddress, 1611 recordSource); 1612 break; 1613 default: 1614 Slog.w(TAG, "Invalid source type:" + recorderAddress); 1615 announceClearTimerRecordingResult(CLEAR_TIMER_STATUS_FAIL_TO_CLEAR_SELECTED_SOURCE); 1616 return; 1617 1618 } 1619 mService.sendCecCommand(message, new SendMessageCallback() { 1620 @Override 1621 public void onSendCompleted(int error) { 1622 if (error != Constants.SEND_RESULT_SUCCESS) { 1623 announceClearTimerRecordingResult( 1624 CLEAR_TIMER_STATUS_FAIL_TO_CLEAR_SELECTED_SOURCE); 1625 } 1626 } 1627 }); 1628 } 1629 1630 void updateDevicePowerStatus(int logicalAddress, int newPowerStatus) { 1631 HdmiDeviceInfo info = getCecDeviceInfo(logicalAddress); 1632 if (info == null) { 1633 Slog.w(TAG, "Can not update power status of non-existing device:" + logicalAddress); 1634 return; 1635 } 1636 1637 if (info.getDevicePowerStatus() == newPowerStatus) { 1638 return; 1639 } 1640 1641 HdmiDeviceInfo newInfo = HdmiUtils.cloneHdmiDeviceInfo(info, newPowerStatus); 1642 // addDeviceInfo replaces old device info with new one if exists. 1643 addDeviceInfo(newInfo); 1644 1645 invokeDeviceEventListener(newInfo, HdmiControlManager.DEVICE_EVENT_UPDATE_DEVICE); 1646 } 1647 1648 @Override 1649 protected boolean handleMenuStatus(HdmiCecMessage message) { 1650 // Do nothing and just return true not to prevent from responding <Feature Abort>. 1651 return true; 1652 } 1653 1654 @Override 1655 protected void dump(final IndentingPrintWriter pw) { 1656 super.dump(pw); 1657 pw.println("mArcEstablished: " + mArcEstablished); 1658 pw.println("mArcFeatureEnabled: " + mArcFeatureEnabled); 1659 pw.println("mSystemAudioActivated: " + mSystemAudioActivated); 1660 pw.println("mSystemAudioMute: " + mSystemAudioMute); 1661 pw.println("mAutoDeviceOff: " + mAutoDeviceOff); 1662 pw.println("mAutoWakeup: " + mAutoWakeup); 1663 pw.println("mSkipRoutingControl: " + mSkipRoutingControl); 1664 pw.println("CEC devices:"); 1665 pw.increaseIndent(); 1666 for (HdmiDeviceInfo info : mSafeAllDeviceInfos) { 1667 pw.println(info); 1668 } 1669 pw.decreaseIndent(); 1670 } 1671} 1672